aja*_*221 17 javascript arrays
我正在尝试创建一个removeAll()函数,它将删除具有该特定值(而不是索引)的数组的所有元素.
当我们对循环进行任何更改时,棘手的部分就出现了,索引往往会移动(使得它很难使它像我们想要的那样工作),并且每次进行更改时重新启动循环在大数组上都是非常低效的.
到目前为止,我编写了自己的arr.indexOf函数(对于较旧的IE支持),它看起来像这样:
function arrFind(val, arr) {
for (var i = 0, len = arr.length, rtn = -1; i < len; i++) {
if (arr[i] === val) {
return i;
}
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
删除这样的元素很容易:
var myarray = [0, 1, 2, 3, 4];
var tofind = 2;
var stored_index = arrFind(tofind, myarray);
if (stored_index != -1) {
myarray.splice(stored_index, 1);
}
alert(myarray.join(",")); //0,1,3,4
Run Code Online (Sandbox Code Playgroud)
但是,正如我之前指出的那样,在循环时执行此操作时,我们遇到了麻烦.
有关如何在循环中正确删除数组项的任何想法?
ken*_*bec 23
每个新浏览器都有一个Array过滤方法:
var myarray=[0,1,2,3,4];
var removal=2;
var newarray=myarray.filter(function(itm){return itm!==removal});
Run Code Online (Sandbox Code Playgroud)
小智 5
试试这个。您只需检查要删除的数字的索引即可。我在你的数组中添加了额外的元素。
var myarray = [0, 1, 2, 3, 2, 2, 2, 5, 6];
var indicesToRemove = new Array();
for(i=0;i<myarray.length;i++){
if(myarray[i]===2){ //let's say u wud like to remove all 2
indicesToRemove.push(i); //getting the indices and pushing it in a new array
}
}
for (var j = indicesToRemove.length -1; j >= 0; j--){
myarray.splice(indicesToRemove[j],1);
}
alert(JSON.stringify(myarray)); //myarray will be [0,1,3,5,6]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27021 次 |
| 最近记录: |