javascript数组 - 访问json类型的对象

时间:2013-01-31 19:25:55

标签: javascript

代码:


function getDummyDetails(){
 var userDetailsMap = [];
 userDetailsMap.push({key:'APPCODE', value:'41'});
 userDetailsMap.push({key:'WORKERNUMBER', value:'1234567'});
 userDetailsMap.push({key:'ACCOUNTID', value:'DEVELOP'});
 userDetailsMap.push({key:'NAMEFIRST', value:'John'});
 userDetailsMap.push({key:'NAMELAST', value:'Developer'});

return userDetailsMap;

}

 function someOtherFunction () {

var userDetails = getDummyDetails();  
document.getElementById("userName").innerHTML = "User Name: " + userDetails[3].value + ", " + userDetails[4].value;

}


这里,它工作正常,但我不能像userDetails [3] .value一样使用数组索引。我试图做这样的事情

 userDetails["APPCODE"].value; // just a pseudo code

如何使用该字符串值但不是整数来索引此数组?

3 个答案:

答案 0 :(得分:3)

您应该创建一个对象而不是数组。这样你就可以通过它的密钥访问它:

function getDummyDetails() {
    return {
        'APPCODE':'41',
        'WORKERNUMBER':'1234567',
        'ACCOUNTID':'DEVELOP',
        'NAMEFIRST':'John',
        'NAMELAST':'Developer'
    };
}

function someOtherFunction () {
    var userDetails = getDummyDetails();  
    userDetails["APPCODE"] // 41 - use it however you want...
}

答案 1 :(得分:1)

您需要创建一个对象,而不是数组:

var userDetailsMap = {
  APPCODE:41
}

var value = userDetailsMap["APPCODE"];//value now = 41

答案 2 :(得分:1)

如果您不想更改结构,可以迭代阵列:

for (var i = 0, len = userDetailsMap.length; i < len; i++) {
  if (userDetailsMap[i].key == 'APPCODE') {
    var val = userDetailsMap[i].value;
    // do something with the value here
  } 
}