【发布时间】:2014-12-10 19:17:47
【问题描述】:
我正在尝试创建一个可以从 forEach 循环中删除元素的函数。
功能:
loopAndEdit = function(array,callback) {
var helper = {
data:{},
get:function() {
return helper.data;
},
remove:function() {
index = array.indexOf(helper.data);
array.splice(index,1);
return true;
}
};
tempArray = array;
tempArray.forEach(function(row) {
helper.data = row;
callback(helper)
});
}
为了测试它,我遍历一个数组并尝试删除所有元素:
names = ['abe','bob','chris'];
loopAndEdit(names,function(helper){
console.log('Working on ' + helper.data);
helper.remove();
});
console.log(names);
输出为:
Working on abe
Working on chris
[ 'bob' ]
我希望输出类似于:
Working on abe
Working on bob
Working on chris
[]
我感觉可能是 helper.remove() 造成了麻烦,但我现在不确定。
感谢您的帮助!
【问题讨论】:
标签: javascript arrays node.js foreach