简体   繁体   English

在索引处结束数组映射?

[英]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? 是否可以将参数传递给Array.map()仅上至给定索引? Or is this only possible using a for loop? 还是只能使用for循环?

Just use slice . 只需使用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). slice()方法将数组的一部分的浅表副本返回到从头到尾选择的新数组对象中(不包括end)。 The original array will not be modified. 原始数组将不会被修改。

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

By definition, map() is called on every element in the array. 根据定义,对数组中的每个元素都调用map()。 See the docs for details here . 详情请参阅文档在这里 So, yes, you would need to use a different solution such as a for loop. 因此,是的,您需要使用其他解决方案,例如for循环。

您可以使用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). 您可以使用slice()函数,该函数将数组的一部分的浅表副本返回到从头到尾选择的新数组对象中(不包括end)。 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 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

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

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