Is element in array js
Following an old question, I still have a problem:
a = ["apple", "banana", "orange", "apple"];
a.indexOf("apple") = 0
What is the easiest way to find BOTH indexes of "apple" element in array? I want to delete them both at once - is it possible?
这是筛选方法的任务:
var noApples = a.filter(function(el) { return el != "apple"; })
What is the easiest way to find BOTH indexes of "apple" element in array?
You asked that, but also asked about deleting. I'll tackle indexes first, then deletion.
Indexes:
There's no shortcut, you have to loop through it. You can use a simple for
loop:
var indexes = [];
var index;
for (index = 0; index < a.length; ++index) {
if (a[n] === "apple") {
indexes.push(index);
}
});
Or two ES5 options: forEach
:
var indexes = [];
a.forEach(function(entry, index) {
if (entry === "apple") {
indexes.push(index);
}
});
Or reduce
:
var indexes = a.reduce(function(acc, entry, index) {
if (entry === "apple") {
acc.push(index);
}
return acc;
}, []);
...although frankly that does't really buy you anything over forEach
.
Deletion:
From the end of your question:
I want to delete them both at once - is it possible?
Sort of. In ES5, there's a filter
function you can use, but it creates a new array.
var newa = a.filter(function(entry) {
return entry !== "apple";
});
That basically does this (in general terms):
var newa = [];
var index;
for (index = 0; index < a.length; ++index) {
if (a[n] !== "apple") {
newa.push(index);
}
});
Array.indexOf
takes a second, optional argument: the index to start from. You can use this inside a loop to specify to start from the last one.
var indices = [],
index = 0;
while (true) {
index = a.indexOf("apple", index);
if (index < 0) {
break;
}
indices.push(index);
}
Once indexOf
returns -1
, which signals "no element found", the loop will break. The indices
array will then hold the correct indices.
There is an example on the Mozilla page on indexOf
which has some equivalent code. I'm not so much of a fan because of the increased duplication, but it is shorter, which is nice.
上一篇: 引导类型只允许列表值
下一篇: 是数组js中的元素