问题描述:

Here's a short JS function that attempts to retrieve an object from an array and access its only field:

function foo()

{

var fruitLiteral = {name : "Orange"};

var myArray = [];

myArray.push(fruitLiteral);

console.log(" myArray after push " + myArray);

var rc = myArray.splice(0,1);

console.log(" myArray after splice " + myArray);

console.log(rc.name);

}

And the output:

 myArray after push [object Object]

myArray after splice

undefined //wanted to see rc.name, or "Orange" here.

The array appears to have been emptied as expected after the splice, but I always get "undefined" for the item retrieved from the splice when it's a literal object. Where's my error?

网友答案:

The problem is that your fruitLiteral is still stored as the first element of the rc array after splicing so you need to treat it like that.

function foo()
{
    var fruitLiteral = {name : "Orange"};
    var myArray = [];
    myArray.push(fruitLiteral);
    console.log(" myArray after push " + myArray);
    var rc = myArray.splice(0,1);
    console.log(" myArray after splice " + myArray);
    console.log(rc[0].name);
}
相关阅读:
Top