简体   繁体   English

Javascript包含子数组的数组键

[英]Javascript Array keys which holds sub-arrays

I have an array which holds sub-arrays, the main array has custom keys; 我有一个包含子数组的数组,主数组有自定义键; used as an identifier. 用作标识符。 The problem is I can't access the array with these keys set eg: 问题是我无法使用这些键设置访问数组,例如:

array.length - returns 0 when clearly it has values array.length - 当它有值时返回0

In console: 在控制台中:

[evt1: Array[0], evt2: Array[0]] [evt1:Array [0],evt2:Array [0]]
evt1: Array[0] evt1:数组[0]
evt2: Array[0] evt2:数组[0]

When changed back to a standard index (0,1,2), the array can be accessed - and performs as normal. 当更改回标准索引(0,1,2)时,可以访问该数组 - 并且正常执行。 Why is this happening? 为什么会这样?

Thanks 谢谢

As stated in comments, you are not using an array, you are using an object. 如注释中所述,您没有使用数组,而是使用对象。 Use Object.keys(your_object).length to get length, and to travel through indexes: 使用Object.keys(your_object).length来获取长度,并遍历索引:

for(var index in your_object){
    console.log(index,your_object[index]);
} 

You can also do: 你也可以这样做:

var indexes=Object.keys(your_object);
for(var i=0;i<indexes.length;i++){
    console.log(indexes[i], your_object[indexes[i]]);
}

Arrays (like many other things in javascript) can have properties just like objects, however, array properties do not count toward the length of the array. 数组(与javascript中的许多其他内容一样)可以具有与对象类似的属性,但是,数组属性不计入数组的长度。 What you should use is an object as the outer structure that contains your keys->arrays. 你应该使用的是一个对象作为包含你的keys->数组的外部结构。

{evt1: Array[0], evt2: Array[0]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM