我有这个数组:
var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
我想知道是否有某种方式创建一个新数组只有当它们的总和小于使用循环或其他东西的全局数组时,例如
var dia = 122;
var dia_new = [31, 28, 31, 30]; //This because they sum less than the given var (dia).
感谢您的回答
答案 0 :(得分:1)
for-loop
并在每次迭代中检查计数。dia
,请将该号码推入array
。for(var i = 0; i < mes_dias.length && (count + mes_dias[i] < dia); i++)
var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var dia = 122;
var count = 0;
var array = [];
for(var i = 0; i < mes_dias.length && (count + mes_dias[i] < dia); i++) {
count += mes_dias[i];
array.push(mes_dias[i]);
}
console.log(array);
&#13;
.as-console-wrapper {
max-height: 100% !important
}
&#13;
如果dia
是一个数字数组,其sum
是新数组的最大天数:
reduce
函数会对array_dia
中的元素求和。
var dia = array_dias.reduce((a, n) => a += n, 0);
var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var array_dias = [30, 30, 31, 31];
var dia = array_dias.reduce((a, n) => a += n, 0);
console.log(dia)
var count = 0;
var array = [];
for(var i = 0; i < mes_dias.length && (count + mes_dias[i] < dia); i++) {
count += mes_dias[i];
array.push(mes_dias[i]);
}
console.log(array);
&#13;
.as-console-wrapper {
max-height: 100% !important
}
&#13;
答案 1 :(得分:1)
您可以将reduce
数组转换为新数组:
let mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let dia = 120;
let dia_new = mes_dias.reduce( (dia_acc, dias) => {
dia -= dias;
if (dia >= 0)
dia_acc.push(dias);
return dia_acc;
}, []);
编辑1:基于Angel Politis' answer,另一个优雅的解决方案可以是:
let dia_new = mes_dias.slice(0, mes_dias.findIndex( (dias) => (dia -= dias) < 0));
编辑2:基于Ele's answer,这种方式提供相同(如果不是更好)的性能,并且在我看来更具可读性。请记住,在最坏的情况下,我们循环12次。
let array = [],
sum = 0;
// Add days until they sum to more than 'dia'
for(let i = 0; i < mes_dias.length; ++i) {
sum += mes_dias[i];
if (sum > dia)
break;
array.push(mes_dias[i]);
}
答案 2 :(得分:0)
实现目标的一种方法是使用循环:
mes_dias
。sum <= dia
。然后,您可以使用slice
获取数组的部分,直到last
索引。
<强>段:强>
var
arr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], // mes_dias
max = 122, // dia
last,
newArr;
/* Iterate over every element of the array until sum > max and save the index. */
for (let i = 0, sum = 0, l = arr.length; i < l && sum <= max; sum += arr[++i]) {
last = i;
}
/* Get the portion of the array until the index. */
newArr = arr.slice(0, last);
/* Log the result. */
console.log(newArr);
答案 3 :(得分:-1)
var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var dia = 122;
var total = 0;
var newarray = new Array();
for(var i = 0; i < mes_dias.length && (total + mes_dias[i]) <= dia; i++) {
newarray.push(mes_dias[i]);
total = total + mes_dias[i];
console.log(newarray);
}