简体   繁体   中英

How to calculate an array of positions in javascript?

I am a beginner in JavaScript. I have an array of lengths [2,6,8,5] . I would like to calculate another array which would represent the position of each of the elements. ex: [1,3,9,17,22] where 1 is the position of the first element, 3 the position of the second element

(1 + 2), 9 = (1 + 2 + 6) … and 22 (1 + 2 + 6 + 8 + 5) . thank you for your help

I use this but i am not shure this is the best way

 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); 

You could reduce the array and start with the start value of one and take the last element for adding the actual value.

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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