当前位置: 动力学知识库 > 问答 > 编程问答 >

How to retrieve and access fields within javascript object literals from an array?

问题描述:

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);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: