ogo*_*got 2 javascript reduce jquery json
我从Javascript中的JSON文件中获取一系列视频持续时间(以秒为单位),为简化起见,它将如下所示:
array = [30, 30, 30]
Run Code Online (Sandbox Code Playgroud)
我想将每个值添加到前一个值,直到满足条件(总和小于变量x),然后获取要播放的视频数组中的新值和索引位置.
例如,如果x = 62(条件),我想要添加数组中的前两个值(从我的理解,reduce()在这里是合适的),并且index = 2(数组中的第二个视频).
我已经掌握了reduce():
var count = array.reduce(function(prev, curr, index) {
console.log(prev, curr, index);
return prev + curr;
});
Run Code Online (Sandbox Code Playgroud)
但似乎无法超越这一点..谢谢
Nin*_*olz 10
你可以使用Array#some,在一个条件下打破.
var array = [30, 30, 30],
x = 62,
index,
sum = 0;
array.some(function (a, i) {
index = i;
if (sum + a > x) {
return true;
}
sum += a;
});
console.log(index, sum);Run Code Online (Sandbox Code Playgroud)
具有紧凑的结果和这个args
var array = [30, 30, 30],
x = 62,
result = { index: -1, sum: 0 };
array.some(function (a, i) {
this.index = i;
if (this.sum + a > x) {
return true;
}
this.sum += a;
}, result);
console.log(result);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2464 次 |
| 最近记录: |