[英]How do I access a Javascript 2D array of objects?
I have a global array that I declare as 我有一个全局数组,我声明为
var fileMappings = [];
I do some work, and add a row to the array like so: 我做了一些工作,然后像这样向数组添加一行:
fileMappings.push({ buttonNumber: number, audioFile: file });
if I do a JSON.stringify(fileMappings) I get this: 如果我做一个JSON.stringify(fileMappings)我得到这个:
[{“buttonNumber”:”btn11”,”audioFile”:{0A0990BC-8AC8-4C1C-B089-D7F0B30DF858}},
{“buttonNumber”:”btn12”,”audioFile”:{2FCC34A6-BD1A-4798-BB28-131F3B546BB6}},
{“buttonNumber”:”btn13”,”audioFile”:{53A206EC-7477-4E65-98CC-7154B347E331}}]
How can I access the GUID for "btn11", etc? 如何访问“ btn11”等的GUID?
Since Javascript arrays don't have support for keys, I would suggest that you use an object. 由于Javascript数组不支持键,因此建议您使用一个对象。 Otherwise, you have to iterate through the entire array every time to look for the desired key.
否则,您每次都必须遍历整个数组以查找所需的密钥。
var fileMappings = {};
And instead of push()
, define a new property : 而不是
push()
,定义一个新属性:
fileMappings[number] = { buttonNumber: number, audioFile: file };
This way, you can access your object with fileMappings['btn11']
这样,您可以使用
fileMappings['btn11']
访问对象
You can iterate over the array's members to find the button, then return its GUID: 您可以遍历数组的成员以找到按钮,然后返回其GUID:
function findGUID(arr, buttonNumber) {
for (var i=0, iLen=arr.length; i<iLen; i++) [
if (arr[i].buttonNumber == buttonNumber) {
return arr[i].audioFile;
}
}
// return undefined - buttonNumber not found
}
Or if you want to use ES5 features: 或者,如果您想使用ES5功能:
function getGUID(arr, buttonNumber) {
var guid;
arr.some(function(obj) {
return obj.buttonNumber == buttonNumber && (guid = obj.audioFile);
});
return guid;
}
but I think the first is simpler and easier to maintain. 但我认为第一种方法更容易维护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.