[英]How do I loop through 2d array if I do not know the indexes
My array looks like this: 我的数组如下所示:
var permissions = new Array();
permissions['role-1'] = new Array();
permissions['role-1']['permission-1'] = "perm1";
permissions['role-1']['permission-3'] = "perm3";
permissions['role-1']['permission-5'] = "perm5";
permissions['role-2']['permission-1'] = "perm1";
permissions['role-2']['permission-5'] = "perm5";
How would I loop through such an array and go through all the elements? 我将如何遍历这样的数组并遍历所有元素? I can't use for-loop since that would use integer indexes.
我不能使用for循环,因为那样会使用整数索引。
You are confusing arrays (which are best suited to integer-indexed properties) with objects (which are designed to use any valid string as a property name). 您会将数组(最适合整数索引的属性)与对象(旨在使用任何有效字符串作为属性名称)混淆。 Objects are sometimes called "associative arrays," which makes the distinction a bit confusing.
对象有时称为“关联数组”,这使得区分有些混乱。
Instead of using new Array()
, you should use the object literal shorthand to initialize your permissions
variable. 代替使用
new Array()
,您应该使用对象文字速记来初始化您的permissions
变量。 Then, you can use Object.keys
to get a list of the keys you used to create your object and do something with your key-value pairs: 然后,您可以使用
Object.keys
来获取用于创建对象的键的列表,并对键值对进行某些操作:
var permissions = { 'role-1': { 'permission-1': 'perm1', 'permission-3': 'perm3', 'permission-4': 'perm1', 'permission-5': 'perm5', }, 'role-2': { 'permission-1': 'perm1', 'permission-5': 'perm5' } } var object = permissions['role-1'] Object.keys(object).forEach(function (key) { // Do something with your key-value pairs console.log(key, this[key]) }, object)
For more information, see "How do I loop through or enumerate a JavaScript object?" 有关更多信息,请参见“如何循环浏览或枚举JavaScript对象?”
I would use an object
to store that. 我会使用一个
object
来存储它。
var permissions = {};
permissions['role-1'] = permissions['role-1'] || {};
permissions['role-1']['permission-1'] = "perm1";
permissions['role-1']['permission-3'] = "perm3";
Then you can iterate over the keys
然后您可以遍历
keys
for(var key in permissions)
console.log(permissions[key]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.