如何获取数组的每个第三个元素 [英] How to take every 3rd element of an array
本文介绍了如何获取数组的每个第三个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,只想将每三个元素作为一个新数组返回(从0开始).
I have an array, and want to return only every third element as a new array (starting at 0).
例如:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArr = [1, 4, 7];
这是我目前正在这样做的方式:
This is the way I am currently doing this:
let newArr = [];
for(let x = 0; x < arr.length; x += 3) {
newArr.push(arr[x]);
}
return newArr;
有没有办法用arr.map做到这一点?有没有更简单的方法可以做到这一点?
Is there a way to do this with arr.map? Is there just an easier way to do this?
推荐答案
You can alternatively do it with a filter
,
let newArr = arr.filter((_,i) => i % 3 == 0);
但是请记住,在某些情况下,使用基本的for循环要比其他方法更有效率.
But remember, using basic for loop is bit more efficient than others in some contexts.
这篇关于如何获取数组的每个第三个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文