Pro*_*der 11 javascript jquery
在一个老问题之后,我仍然有一个问题:
a = ["apple", "banana", "orange", "apple"];
a.indexOf("apple") = 0
Run Code Online (Sandbox Code Playgroud)
在数组中找到"apple"元素的BOTH索引的最简单方法是什么?我想立刻删除它们 - 这可能吗?
c-s*_*ile 15
这是过滤方法的任务:
var noApples = a.filter(function(el) { return el != "apple"; })
Run Code Online (Sandbox Code Playgroud)
在数组中找到"apple"元素的BOTH索引的最简单方法是什么?
你问过,还问过删除.我会首先处理索引,然后删除.
没有捷径,你必须循环它.你可以使用一个简单的for循环:
var indexes = [];
var index;
for (index = 0; index < a.length; ++index) {
if (a[n] === "apple") {
indexes.push(index);
}
});
Run Code Online (Sandbox Code Playgroud)
或者两个ES5选项forEach:
var indexes = [];
a.forEach(function(entry, index) {
if (entry === "apple") {
indexes.push(index);
}
});
Run Code Online (Sandbox Code Playgroud)
或者reduce:
var indexes = a.reduce(function(acc, entry, index) {
if (entry === "apple") {
acc.push(index);
}
return acc;
}, []);
Run Code Online (Sandbox Code Playgroud)
...虽然坦率地说这并没有真正给你买任何东西forEach.
从问题的最后:
我想立刻删除它们 - 这可能吗?
有点.在ES5中,filter您可以使用一个函数,但它会创建一个新数组.
var newa = a.filter(function(entry) {
return entry !== "apple";
});
Run Code Online (Sandbox Code Playgroud)
这基本上是这样的(一般来说):
var newa = [];
var index;
for (index = 0; index < a.length; ++index) {
if (a[n] !== "apple") {
newa.push(index);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
775 次 |
| 最近记录: |