在javascript中,如何从对象数组中删除元素?

时间:2010-07-12 19:11:15

标签: javascript jquery jquery-ui jquery-plugins

在javascript中,如何从对象数组中删除元素? 这是代码:

$.fn.mapImage.deletePinpoint = function(image, pinpoint){
    var deleted = false;
    for (var i = 0; i < image.pinpoints.length; i++) {
        if(image.pinpoints[i].position == pinpoint.position){
            image.pinpoints.remove(i);
            deleted = true;
        }
        if(deleted){
            image.pinpoints[i].position -= 1;
        }
    }
    $('.edit-mode').find('div.dynamic-pinpoint-area').remove();
    $('.edit-mode').find('div.pinpoint-text').remove();
    $('.create-mode').find('div.static-pinpoint-area').remove();
    $('.create-mode').find('div.pinpoint-text').remove();

    $.fn.mapImage.load(image);

}

image.pinpoints是对象数组。再次感谢你们!

3 个答案:

答案 0 :(得分:4)

请参阅https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator

e.g。 (来自消息来源)

var trees = ["redwood","bay","cedar","oak","maple"];  
delete trees[3];  
if (3 in trees) {  
   // this does not get executed  
}  

答案 1 :(得分:1)

我认为你应该更清楚地重述这个问题。在您的示例中,如果image.pinpoints属性与position的属性匹配,则可能会从pinpoint数组中删除多个元素。因此,它会删除image.pinpoints[i].position == pinpoint.positioni0的每个(image.pinpoints.length - 1)

由于您也在同时迭代数组,我不建议单独使用splice。而是首先delete每个索引,然后在第二次传递中清理数组。

splicedelete的工作方式不同,因为删除会在数组中创建一个洞,并将已删除属性的值设置为undefined。另一方面,splice将删除该元素,就好像它从未存在一样,并将其后的所有元素的索引修复为连续。考虑这个例子:

> var a = [2,3,5,7,11]; // create an array of 5 elements
> undefined
> a[2] // see the value of the third element
> 5
> delete a[2] // delete the third element using "delete"
> true
> a // log contents of a
> [2, 3, undefined, 7, 11]
> a[2] // index 2 still exists with value "undefined" now
> undefined

splice这里本身也存在问题,就像删除一个元素一样,该元素之后的所有索引都会向上移动一个元素,你将跳过检查下一个元素。考虑第二个例子:

> var a = [2,3,5,7,11]; // create array of 5 elements
> for(var i = 0; i < a.length; i++) { 
    if(a[i] == 3 || a[i] == 5) { // if it's 3 or 5, take it out
        a.splice(i, 1);
    }
}
> a
[2, 5, 7, 11]; // yikes, 5 still exists

在上面的示例中,5仍然存在,因为我们从未检查过该值。当我们看到3时,当前索引为1。在拼接数组之后,下一个元素 - 5向上移动以取得它的位置并成为索引1。由于我们此时已完成索引1,因此我们只需转到下一个索引 - 2,现在其值为7,并跳过5。通常,使用索引进行迭代并进行就地删除不是一个好习惯。

作为一个解决方案,我会创建一个新数组,只插入不要删除的属性。

$.fn.mapImage.deletePinpoint = function(image, pinpoint) {
    // will hold all objects that are not to be deleted
    var remainingPinpoints = [];

    for (var i = 0; i < image.pinpoints.length; i++) {
        // reverse condition
        if(image.pinpoints[i].position != pinpoint.position) {
            // add to new array
            remainingPinpoints.push(image.pinpoints[i]);
        }
    }

    // assign new array to pinpoints property
    image.pinpoints = remainingPinpoints;

    ...
}

答案 2 :(得分:1)

.splice是w3schools.com上提供的方法http://www.w3schools.com/jsref/jsref_splice.asp 要从索引为x的数组中删除一个元素,您将拥有trees.splice(x,x+1);这将删除x并在需要时返回它。

相关问题