javascript - 当我在这个数组上使用 forEach 时,如何从数组中删除一个项目?
问题描述
我有一个包含函数/对象的数组。此对象具有测试自身的功能,如果它们失败,它们会从数组中删除。如果我在这个数组上运行一个 forEach 并运行这个 testfunction 并且一个对象从数组中删除,那么 forEach 循环会跳过一个对象。
解决这个问题的好方法是什么?
这里举个例子。运行示例,您将看到tests.push(new Test(2));
在 forEach 循环中跳过了 2ed 对象。
//creating a test array
var tests = [];
tests.push(new Test(1));
tests.push(new Test(2));
tests.push(new Test(3));
tests.push(new Test(4));
function Test(n) {
this.n = n;
this.testme = function() {
if(this.n < 3) {
tests.splice(tests.indexOf(this), 1); //remove me from the array tests please!
console.log(this.n, "I got removed!");
} else {
console.log(this.n, "I can stay!");
}
}
}
console.log("tests length: ", tests.length);
tests.forEach(function(t) {
t.testme();
});
console.log("tests length: ", tests.length); //output should now be 2
解决方案
为什么不使用内置filter
功能?
tests = tests.filter(t => t.testMe());
推荐阅读
- python - Odoo 11 - 过滤 Many2One 字段
- javascript - 有没有办法在函数中模拟 Promise.resolve
- matlab - 多次迭代后 MATLAB 中的 trainNetwork 出现错误:连接的数组维度不一致?
- reactjs - 为什么我的 React 本机 route.params 保存以前的路由数据?
- android - Flutter 移动应用程序中的 Flurry 崩溃报告
- flutter - 试图停止计时器但计时器没有停止
- php - 运行 PHPUnit 测试时无法加载 Xdebug
- android - 当我使用 viewmodel 时,为什么 onClick 方法不调用 ratingBar?
- python - 将数组字符串值添加到 pandas.DataFrame 时,它们会转换为浮点数
- telegram - 如何使用 python-telegram-bot (Bot API 5.1) 跟踪用户何时踢出 Telegram Bot