/* *在抽獎的活動中常常會用到這個算法,不一樣獎項的獲取機率不一樣,要按機率去隨機生成對應的獎品 * */ function random(arr1, arr2) { var sum = 0, factor = 0, random = Math.random(); for(var i = arr2.length - 1; i >= 0; i--) { sum += arr2[i]; // 統計機率總和 }; random *= sum; // 生成機率隨機數 for(var i = arr2.length - 1; i >= 0; i--) { factor += arr2[i]; if(random <= factor) return arr1[i]; }; return null; }; // test var a = ['mac', 'iphone', 'vivo', 'OPPO']; var b = [0.1, 0.2, 0.3, 0.4]; console.log(random(a, b));