简体   繁体   中英

End array map at an index?

Is it possible to only map an array up to a certain index?

For example, say I have the following:

var nums = [1, 2, 3, 4, 5];

I want to sum up the numbers in the array, but only up to the 3rd index. Is it possible to pass in an argument to Array.map() to only go up to a given index? Or is this only possible using a for loop?

Just use slice .

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

nums.slice(0,3).map(...);

By definition, map() is called on every element in the array. See the docs for details here . So, yes, you would need to use a different solution such as a for loop.

您可以使用slice()获取数组直到特定索引

nums.slice(0,3).map();

you can use slice() function which returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

nums.slice(0,3).map(//your code);

for more information

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

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