0

编码:


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

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

4

3 回答 3

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...
}
于 2013-01-31T19:27:16.833 回答
1

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

var userDetailsMap = {
  APPCODE:41
}

var value = userDetailsMap["APPCODE"];//value now = 41
于 2013-01-31T19:28:11.903 回答
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
  } 
}
于 2013-01-31T19:29:23.127 回答