繁体   English   中英

如何在javascript中计算位置数组?

[英]How to calculate an array of positions in javascript?

我是JavaScript的初学者。 我有一个长度为[2,6,8,5]的数组。 我想计算另一个数组,它将代表每个元素的位置。 例如: [1,3,9,17,22]其中1是第一个元素的位置,3是第二个元素的位置

(1 + 2), 9 = (1 + 2 + 6) … and 22 (1 + 2 + 6 + 8 + 5) 谢谢您的帮助

我用这个但是我不敢肯定这是最好的方法

 var lengthOfWords = [2,6,8,5]; var subPosition = 0 ; var positionOfWords = [1] for (var x = 0; x < lengthOfWords.length; x++) { subPosition += lengthOfWords[x]; positionOfWords[x+1] = subPosition +1 ; } console.log(positionOfWords); 

您可以减少数组,并以1的起始值开始,并使用最后一个元素添加实际值。

 last a sum result ---- ---- ---- --------------- 1 1 2 3 1, 3 3 6 9 1, 3, 9 9 8 17 1, 3, 9, 17 17 5 22 1, 3, 9, 17, 22 

 var array = [2, 6, 8, 5], result = array.reduce((r, a) => r.concat(r[r.length - 1] + a), [1]); console.log(result); 

ES5

 var array = [2, 6, 8, 5], result = array.reduce(function (r, a) { return r.concat(r[r.length - 1] + a); }, [1]); console.log(result); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM