[英]don't get return associative array in javascript
When i create associate array in javascript, i got a problem like that. 当我在javascript中创建关联数组时,出现了这样的问题。 I want to get the value by using field name as key, but i just only got undefined. 我想通过使用字段名称作为键来获取值,但是我只是未定义而已。 What should i do to get value by key or which way is good approach for it. 我应该怎么做才能获得关键的价值,或者哪种方法是实现目标的好方法。
Here is my code 这是我的代码
function getFields(pVal){
var tmpObj = {};
str = pVal.split(",");
for(i=0;i<str.length;i++){
tmpVal = str[i].split(":");
tmpObj[tmpVal[0]] = tmpVal[1];
}
return tmpObj;
}
function JustTest(){
var fields = {};
fields = getFields("'Code':'PRJ001','Name':'Project 01'");
alert(fields['Code']);
}
Because the key is 'Code'
, not Code
, note the single quote '
, you need do alert(fields["'Code'"]);
因为键是'Code'
而不是Code
,请注意单引号'
,您需要执行alert(fields["'Code'"]);
PS: Please add ;
PS:请添加;
at the end of statement, it is bad practice to omit them. 在声明的末尾,忽略它们是不好的做法。
I have re-factor the code, just try this: 我已经重构了代码,只需尝试以下操作:
function getFields(pVal) {
var tmpObj = {};
var str = pVal.split(",");
for (var i = 0; i < str.length; i++) {
var tmpVal = str[i].split(":");
tmpObj[tmpVal[0]] = tmpVal[1];
}
return tmpObj;
}
function JustTest() {
var fields = { };
fields = getFields("'Code':'PRJ001','Name':'Project 01'");
alert(fields["'Code'"]);
}
if you have question please comment below about code, thanks 如果您有任何疑问,请在下面评论代码,谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.