0

我正在尝试从数组“shapes”中提取一个元素,其中该元素的 id 等于 dragID。我想知道我是否以正确的方式进行操作......这会出现很多问题,例如,有时某些元素会被跳过,同时将它们从保留数组推回真实数组。请告诉我是否有更好的方法来做到这一点..

 var reserveShapes = [];
    while(1)
    {
        drag = shapes.pop();
        if(drag.id == dragID)
        {
             break;
        }
        reserveShapes.push(drag);   
    }

    //alert(reserveShapes.length);
    for(var j=0; j<reserveShapes.length; j++)
    {
        ar temp = reserveShapes.pop();
        shapes.push(temp);
    }
4

2 回答 2

3

Wow. Your idea may work, but there's a much cleaner way:

var drag;
for (int i = 0; i < shapes.length; i++) {
    if (shapes[i].id == dragID) {
         drag = shapes[i];
         break;
    }
}

if (drag) {
    // a matching shape was found
    // ...
}

If you want to remove that element from its position in the array, use splice:

    if (shapes[i].id == dragID) {
        drag = shapes.splice(i, 1);
        break;
    }    

You definitely don't have to use push and pop to go through an array.

EDIT References showing you can access an array using []

The reading is kind of dense, but the specification for ECMA-262 (the latest standard to which JavaScript subscribes) is at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf. On page 67, it says:

Properties are accessed by name, using either the dot notation: 
    MemberExpression . IdentifierName 
    CallExpression . IdentifierName 
or the bracket notation: 
    MemberExpression [ Expression ] 
    CallExpression [ Expression ]

The [] accessor is actually allowed on all objects, and arrays are special objects. Page 122 defines an array:

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^ 32 - 1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^ 32.

What this boils down to is "if you use numbers as indices to the properties of an object, that object is treated as an array."

The spec is fairly dense to read, so here are some easier references to using arrays in JavaScript:

于 2013-11-05T19:00:11.273 回答
1

来自 ECMAScript 5 的稍微更现代的方法:

var drag;
shapes = shapes.filter( function (current) {
    if( current.id === dragID ) {
        drag = current;
        return false;
    }

    return true;
} );

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

于 2013-11-05T19:03:27.000 回答