javascript - for 循环行为真的很奇怪

标签 javascript json angularjs

我正在循环中比较 2 个整数,该循环循环遍历包含 JSON 对象的数组。 JSON 对象包含 ID 和名称。当我单击窗口的关闭按钮时,该窗口应该消失,其他窗口应该保留,但会发生的情况是,如果我关闭 ID 最高的窗口,所有窗口都会关闭,例如,如果我关闭第五个窗口,则 #1 -5 被关闭,但更高的 ID 仍然存在。

    ctrl.items = [{
        id: 1,
        name: "Number one"
    },
    {
        id: 2,
        name: "Number two"
    },
    {
        id: 3,
        name: "Number three"
    }];

    ctrl.removeWindow = function(toBeRemovedId) {
        console.log("Called: " + toBeRemovedId);
        for (var i = ctrl.items.length - 1; i >= 0; i--) {
            console.log(ctrl.items[i].id + " " + toBeRemovedId);
            if(ctrl.items[i].id == toBeRemovedId) {
                ctrl.items.splice(ctrl.items[i], 1);
            }
        };
    }

    <div class="window show" id="item_window" ng-repeat="item in itemWindowCtrl.items">
        <hgroup>
            <h1>{{ item.name}}</h1>
            <button class="close" ><span class="fa fa-times fa-lg" ng-click="itemWindowCtrl.removeWindow(item.id)"></span></button>
        </hgroup>
        <section>
            <p>{{ item.id + " " + item.name }}</p>
        </section>
    </div>

预先感谢您能给我带来的任何线索。

最佳答案

数组拼接函数采用索引,而不是要删除的项目,因此您应该这样做:

ctrl.items.splice(i, 1);

不过循环有点不必要。为什么不直接遍历要删除的项目,而不是按 id 降序循环查找匹配的 id?例如:

ng-click="itemWindowCtrl.removeWindow(item)"

然后在你的 Controller /指令中:

ctrl.items.splice(ctrl.items.indexOf(item), 1);

关于javascript - for 循环行为真的很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26565789/

相关文章:

javascript - Pebble AppSync 元组仅使用初始值

java - Spring Boot 使用带有通用字段的类来使用 REST API,该字段未转换为正确的类型。我究竟做错了什么?

javascript - 如何使用 jsawk 从具有非字母数字字符的 json 对象的属性中提取值

javascript - 在 AngularJS 中创建本地存储

angularjs - Videogular Controller 与 onsen UI 一起使用时无法工作

javascript - this 在箭头函数中未定义

javascript - 填充路径取决于绘制顺序

json - 如果文档有数组,如何解决 JQ 处理为多个字典的问题?

ruby-on-rails - Heroku + Rails + Angular = 未知提供商 : eProvider <- e

php - 来自 php 变量的 Google Analytics 自定义变量(动态数字)