Javascript 如何提取数组的偶数元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7243355/
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
How do I extract even elements of an Array?
提问by DrStrangeLove
var arr = [4, 5, 7, 8, 14, 45, 76];
function even(a) {
var ar = [];
for (var i = 0; i < a.length; i++) {
ar.push(a[2 * i + 1]);
}
return ar;
}
alert(even(arr));
http://jsbin.com/unocar/2/edit
http://jsbin.com/unocar/2/edit
I have tried this code in order to output even (index) elements of an array. It works, but it also outputs some empty elements. How do I fix this code to output only existing elements?
我试过这段代码是为了输出数组的偶数(索引)元素。它有效,但它也会输出一些空元素。如何修复此代码以仅输出现有元素?
采纳答案by Felix Kling
Either use modulus:
要么使用模数:
for (var i = 0; i < a.length; i++) {
if(i % 2 === 0) { // index is even
ar.push(a[i]);
}
}
or skip every second element by incrementing i
accordingly:
或通过相应地递增跳过每个第二个元素i
:
for(var i = 0; i < a.length; i += 2) { // take every second element
ar.push(a[i]);
}
Notice:Your code actually takes the elements with oddindexes from the array. If this is what you want you have to use i % 2 === 1
or start the loop with var i = 1
respectively.
注意:您的代码实际上从数组中获取具有奇数索引的元素。如果这是你想要的,你必须分别使用i % 2 === 1
或开始循环var i = 1
。
回答by naveen
For IE9+ use Array.filter
对于 IE9+ 使用 Array.filter
var arr = [4,5,7,8,14,45,76];
var filtered = arr.filter(function(element, index, array) {
return (index % 2 === 0);
});
With a fallback for older IEs, all the other browsers are OK without this fallback
有了旧 IE 的回退,所有其他浏览器都可以没有这个回退
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
回答by sumit
This will work on 2018 :)
这将在 2018 年生效:)
take the odd indexes and apply to filter
取奇数索引并应用于过滤器
var arr = [4, 5, 7, 8, 14, 45, 76,5];
let filtered=arr.filter((a,i)=>i%2===1);
console.log(filtered);
回答by eltuza
why don't you try with the % operator. It gives you the remaining of a division.
为什么不尝试使用 % 运算符。它给你一个师的剩余部分。
replace the loop block with
将循环块替换为
if ((i % 2) === 0) {
ar.push(a[i])
}
回答by jkebinger
You need to test the elements for evenness like this:
您需要像这样测试元素的均匀性:
var arr = [4,5,7,8,14,45,76];
function even(a){
var ar = [];
for (var i=0; i<a.length;i++){
if (a[i] % 2 === 0)
{
ar.push(a[i]);
}
}
return ar;
}
alert(even(arr));
%2 is the modulo operator, it returns the remainder of integer division.
%2 是模运算符,它返回整数除法的余数。
回答by mithunsatheesh
var arr = [4,5,7,8,14,45,76];
function even(a)
{
var ar = [];
for (x in a)
{
if((a[x]%2)==0)
ar.push(a[x]);
}
return ar;
}
alert(even(arr));
回答by DadiBit
Even if this question is quite old, I would like to add a one-liner filter:
Odd numbers: arr.filter((e,i)=>i%2)
Even numbers: arr.filter((e,i)=>i%2-1)
A more 'legal' way for even numbers: arr.filter((e,i)=>!(i%2))
即使这个问题已经很老了,我还是想添加一个单行过滤器:
奇数:arr.filter((e,i)=>i%2)
偶数:偶数的arr.filter((e,i)=>i%2-1)
一种更“合法”的方式:arr.filter((e,i)=>!(i%2))
There's no need to check with i%2===1
like sumit said; as mod 2
already returns a 0 or a 1 as numbers, they can be interpreted as boolean values in js.
没有必要i%2===1
像 sumit 所说的那样检查;由于mod 2
已经返回 0 或 1 作为数字,它们可以在 js 中解释为布尔值。
回答by Mike
I just wanted to explain why your result is not what you expected since everyone else shows excellent solutions. You are iterating over an array size N so your resulting array will attempt to push elements in an array that will result in size N. Since only N/2 will be found in the original array your resulting array will fill the rest with blanks to fill in the rest of N. So if you checked to see if a[2*i] exists OR checked to see if a[i] % 2 == 0 before inserting, your resulting array will contain only the even indexed values
我只是想解释为什么你的结果不是你所期望的,因为其他人都展示了出色的解决方案。您正在迭代大小为 N 的数组,因此生成的数组将尝试将数组中的元素推送到大小为 N 的数组中。由于在原始数组中只能找到 N/2,因此生成的数组将用空白填充其余部分以进行填充在 N 的其余部分。因此,如果您在插入前检查 a[2*i] 是否存在或检查 a[i] % 2 == 0 是否存在,则结果数组将仅包含偶数索引值