admin 管理员组文章数量: 1086019
I need this table .html#details in my program and I'm not even sure if an associative array is the way to go.
Given the type (numeric/alphanumeric), number of characters and EC (error correction) level, I want a function to return the version (first column).
I need this table http://code.google./apis/chart/docs/gallery/qr_codes.html#details in my program and I'm not even sure if an associative array is the way to go.
Given the type (numeric/alphanumeric), number of characters and EC (error correction) level, I want a function to return the version (first column).
Share Improve this question edited Oct 13, 2016 at 8:58 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 21, 2010 at 4:13 Mr Rab LorcsMr Rab Lorcs 231 silver badge3 bronze badges 01 Answer
Reset to default 8First, JavaScript has "Arrays" and "Objects". By 'associative array' I assume you mean a JavaScript Object, using keys other than non-negative integers.
You can create JavaScript object literals using syntax such as the following:
var versions = {
"1" : {
rowcols : [21,21],
charsByECLevel : {
L : {
digits:41,
alpha:25
},
M : {
digits:34,
alpha:20
}
}
},
"2" : {
rowcols : [25,25],
charsByECLevel : {
L : {
digits:77,
alpha:47
},
M : {
digits:63,
alpha:48
}
}
}
};
You would then access the properties like so:
console.log( versions[1].charsByECLevel.L.digits );
// 41
To loop through the values, you could do this:
function findVersion( versions, level, digits ){
for (var versionNumber in versions){
if (versions.hasOwnProperty(versionNumber)){
if (versions[versionNumber].charsByECLevel[level].digits == digits){
return versionNumber;
}
}
}
}
findVersion( versions, "L", 77 );
// returns "2"
Edit: Having written the above, if you only want to look up versions based on level and digits, you should probably reverse the hash. Instead of looping through and checking the versions, index them directly and look it up in constant time:
var versionByLevelAndDigits = {
L : {
41 : 1,
77 : 2,
127 : 3
},
M : {
34 : 1,
63 : 2,
101 : 3
}
};
var version = versionByLevelAndDigits["L"][77];
// 2
本文标签: How to use a complex associative array in javascriptStack Overflow
版权声明:本文标题:How to use a complex associative array in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744076395a2529431.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论