在javascript中从数组中删除 [英] Delete from array in javascript

查看:103
本文介绍了在javascript中从数组中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

3小时前,我在SO中提出一个问题,关于删除某个对象的一部分,所以我将这个问题与它联系起来:

3 hours ago, I asked a question in SO , about deleting a part of an object, so I linked this question to it:

在javascript中删除对象的一部分

但是现在当我从该数组中删除时出现了另一个问题。
我使用该对象来填充FlexiGrid。但是当我通过以下代码从该对象中删除一个项目,而不是删除该项目时,它设置为undefined :(并且flexigrid不接受它用于输入数据。

but now another problem occurred when I deleteed from that array. I use that object to populate a FlexiGrid. but when I delete an item from that object by following code, instead of delete that item , it sets to undefined :( and flexigrid did not accept it for input data.

for (var i = 0; i < Roomdata.length; i++) {

    if(Roomdata[i].id = X) {

        delete Roomdata[i];
        break;

    }
}                

例如,假设我在Roomdata中有3个项目,如下所示:

For example, imagine I have 3 items in Roomdata like this :

{item1, item2, item3}

当我调用此代码删除item2时,Roomdata对象如下所示:

When I call this code to delete item2 , Roomdata object looks like this :

{item1, undefined, item3}

这是一个错误的格式,被flexigrid接受为输入数据

and this is a bad format to be accepted by flexigrid as input data

有没有解决方案?

感谢每一个人,抱歉我的语法不好(我是英文新手)

Thanks every body and sorry about my bad syntax (I am new in English)

问候,Foroughi

regards , Foroughi

推荐答案

以相反的顺序遍历数组,并使用 .splice 删除元素。

你必须按相反的顺序行走,因为否则你最终会跳过元素见下文

Walk through the array in reverse order, and use .splice to remove the element.
You have to walk in the reverse order, because otherwise you end up skipping elements See below.

for (var i = Roomdata.length-1; i >= 0; i--) {
    if (Roomdata[i].id == X) {
        Roomdata.splice(i, 1);
        break;
    }
}

如果你不反向行走会怎样order:

What happens if you don't walk in the reverse order:

// This happens in a for(;;) loop:
// Variable init:
var array = [1, 2, 3];
var i = 0;

array.splice(i, 1); // array = [2, 3]   array.length = 2
// i < 2, so continue
i++;  // i = 1    

array.splice(i, 1); // i=1, so removes item at place 1: array = [2]
// i < 1 is false, so stop.

// array = [2]. You have skipped one element.

这篇关于在javascript中从数组中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆