简体   繁体   English

删除元素后重新排列数组

[英]Reorder the array after removing an element

In my application I'm having a list of items which will be pushed into an array when checking that and will be removed from the array when unchecked. 在我的应用程序中,我有一个项目列表,这些项目将在检查时推送到数组中,而在未选中时将从数组中删除。 Here is the code 这是代码

          if (data.selectedInsertion === true) {
                order.push(data);
            }
            else if (data.selectedInsertion === false) {
                angular.forEach(order, function (value,key) {
                    if (value == data) {
                        delete order[key];
                    }
                })
            }

The problem is when the 5th element in the array is deleted, the array will be missing that key forever and so when I display it in the template using angularjs it will show a blank row in the place or the missing 5th element.How can I re arrange the array after removing the element. 问题是当删除数组中的第5个元素时,数组将永远丢失该键,因此当我使用angularjs在模板中显示它时,它将在该位置显示空白行或缺少的第5个元素。删除元素后重新排列数组。

if (data.selectedInsertion === true) {
    order.push(data);
}
else if (data.selectedInsertion === false) {
    order.splice(order.index(data),1);
}

Assuming that all the values in your array are unique, you can do it like this: 假设数组中的所有值都是唯一的,则可以这样进行:

if(data.selectedInsertion) {
  order.push(data);
} else {
  order.splice(order.indexOf(data),1)
}

Array.splice removes elements from an array. Array.splice从数组中删除元素。 Check this link for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice 检查此链接以获取更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

If data is not unique, only the first occurence in the array is removed. 如果data不是唯一的,则仅删除阵列中的第一个匹配项。

Also, you can leave out the explicit checks for true and false , especially since it seems to be a boolean value. 另外,您可以省略对truefalse的显式检查,尤其是因为它似乎是布尔值。

Remember one never use delete to remove elements from an array. 记住,永远不要使用delete从数组中删除元素。 As it will remove the element leaving undefined under it's key. 因为它将删除在其键下未定义的元素。 Thus, you can splice it or filter it out. 因此,您可以将其拼接或过滤掉。

Filter it out: 过滤掉:

if (data.selectedInsertion === true) {
    order.push(data);
}
else if (data.selectedInsertion === false) {
    order = order.filter(function(v){
    return v !== data;
    });
}

Splice it 拼接

if (data.selectedInsertion === true) {
    order.push(data);
}
else if (data.selectedInsertion === false) {
    order.splice(order.indexOf(data),1);
}

delete is used to remove a property from an object. delete用于从对象中删除属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM