1 //数组元素叠加 [1,2,3,4,,] -> [1,3,6,10,,,,] 2 function arrOverAdd(arr){ 3 if( !arr || arr.length <= 0){ 4 return []; 5 } else { 6 var temp = []; 7 for(var i = 0;i < arr.length ; i++){ 8 if(i == 0){ 9 temp[i] = parseInt(arr[i]); 10 } else { 11 temp[i] = temp[i-1] + parseInt(arr[i]); 12 } 13 } 14 return temp; 15 } 16 } 17 18 19 /** 20 * 获取数组中最接近的值得index 21 * @param random 随机数 22 * @param weightArray 权重数组 23 * @returns {number} 24 */ 25 function getArrIndex(random,weightArray){ 26 var index = 0; 27 if(random <= weightArray[0]){ 28 return 0; 29 } else if(random >= weightArray[weightArray.length-1]){ 30 index = weightArray.length - 1; 31 return index; 32 } else { 33 for(var i = 0 ;i < weightArray.length; i++){ 34 if(random <= weightArray[i]){ 35 index = i; 36 } else if(random > weightArray[i] && random <= weightArray[i + 1]){ 37 index = i + 1; 38 break 39 } else if (random > weightArray[i] && random <= weightArray[ i + 1] ){ 40 index = i + 1; 41 break; 42 } 43 } 44 } 45 return index; 46 } 47 48 49 var weightArr = [10,20,30,30,10]; 50 51 weightArr = arrOverAdd(weightArr); 52 console.log(weightArr); 53 var totalWeight = weightArr[weightArr.length - 1]; 54 55 var random = Math.random() * totalWeight; 56 console.log(random); 57 var arrIndex = getArrIndex(random,weightArr); 58 console.log(“索引:”+arrIndex);
李晓东 现任职于北京行云智网络科技有限公司,Node.js工程师