我有一个像这样的数组:
[0, 24.646213151927437, 27.737256235827665, 29.08326530612245]
我想用随机数填充大于4的元素之间的每个空间。像这样:
var arr = [0, 24.646213151927437, 27.737256235827665, 29.08326530612245];
var length = arr.length;
for (var j = 0; j < length;) {
var spacebetween = arr[j + 1] - arr[j];
if (spacebetween > 4) {
// fill the space until the sum of numbers is greater than space between
var m = Math.random() * (3 - 1 + 1);
for (k = m; k < spacebetween;) {
arr.splice(j, 0, parseFloat(k));
m = Math.random() * (3 - 1 + 1);
k = k + m;
}
}
j++;
}
console.log(arr);
问题出在splice()
上,索引在变化,我不知道该如何解决。新数字应在数组中按升序排列。
答案 0 :(得分:0)
您可以使用reduce遍历原始数组并将更新推送到累加器,而无需遍历数组(长度会不断变化)
var arr = [0, 24, 27, 29];
var newArr = arr.reduce((accumulator, cur, i) => {
var needTempArr = arr[i + 1] && (arr[i + 1] - cur);
// if need temp array, generate it; otherwise, empty array
var tempArr = needTempArr
? Array(needTempArr).fill(0).map(() => Math.random())
: [];
return accumulator.concat(cur, tempArr);
}, []);
答案 1 :(得分:0)
是否可以在JavaScript的循环期间使用 .splice()添加元素?
是,解决方案是从头开始并递减,新条目将不再干扰该过程:
变化不大于4的间隙
let arr = [ 0, 24.646213151927437, 27.737256235827665, 29.08326530612245 ]
for (let j=arr.length; --j;) // inside loop j start to (arr.length-1) to value==1 ( value zéro mean false)
{
let vRef = arr[j-1]
, vMin = arr[j] -4
;
while (vMin > vRef)
{
vMin = (Math.random()*4) + vMin
arr.splice( j, 0, vMin )
vMin -= 4
}
}
console.log( JSON.stringify( arr,0,2 ))
.as-console-wrapper { max-height: 100% !important; top: 0; }