访问数组中的所有其他项目 - JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30713250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access every other item in an array - JavaScript
提问by Rafill
Is it possible for me to access every other item in an array? So basically, all items in positions 0, 2, 4, 6 etc.
我是否可以访问数组中的所有其他项目?所以基本上,位置 0、2、4、6 等中的所有项目。
Here's my code if it helps:
如果有帮助,这是我的代码:
function pushToHash(key, value) {
for (var t = 0; t < value.length; t++) {
MQHash[key[t]] = value.slice(0, lineLength[t]);
}
}
So, I need to get every other value of lineLength
. I only want this for lineLength
, not key
. I was thinking of doing a modulus, but wasn't sure how I'd implement it. Any ideas?
所以,我需要获得lineLength
. 我只想要这个lineLength
,不是key
。我正在考虑做一个模数,但不确定如何实现它。有任何想法吗?
Thanks in advance!
提前致谢!
采纳答案by T.J. Crowder
If you just want this with lineLength
and not with key
, then add a second variable and use +=
when incrementing:
如果您只想要 withlineLength
而不是 with key
,则添加第二个变量并+=
在递增时使用:
function pushToHash(key, value) {
for (var t = 0, x = 0; t < value.length; t++, x += 2) {
MQHash[key[t]] = value.slice(0, lineLength[x]);
}
}
(The power of the comma operator...)
(逗号运算符的威力……)
回答by dannymac
You can use the index (second parameter) in the array filter method like this:
您可以在数组过滤器方法中使用索引(第二个参数),如下所示:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// filter out all elements that are located at an even index in the array.
let x = arr.filter((element, index) => {
return index % 2 === 0;
})
console.log(x)
// [1, 3, 5, 7, 9]