问题描述
我有这个code创建一个数组:
I have an array created with this code:
var widthRange = new Array();
widthRange[46] = { min:0, max:52 };
widthRange[66] = { min:52, max:70 };
widthRange[90] = { min:70, max:94 };
我想每个值46,66,90在一个循环。我试图为(以widthRange VAR键)
但是这给了我额外的属性的一大堆(我以为他们是在对象上的功能)。因为值不连续的,我不能使用常规的循环。
I want to get each of the values 46, 66, 90 in a loop. I tried for (var key in widthRange)
but this gives me a whole bunch of extra properties (I assume they are functions on the object). I can't use a regular for loop since the values are not sequential.
推荐答案
您需要调用<$c$c>hasOwnProperty$c$c>函数来检查是否该属性的对象本身实际上定义(而不是它的原型),像这样的:
You need to call the hasOwnProperty
function to check whether the property is actually defined on the object itself (as opposed to its prototype), like this:
for (var key in widthRange) {
if (key === 'length' || !widthRange.hasOwnProperty(key)) continue;
var value = widthRange[key];
}
请注意,您需要为长度
单独检查。结果
但是,你不应该在这里使用一个数组的全部;你应该使用常规的对象。所有的JavaScript对象作为关联数组。
Note that you need a separate check for length
.
However, you shouldn't be using an array here at all; you should use a regular object. All Javascript objects function as associative arrays.
例如:
var widthRange = { }; //Or new Object()
widthRange[46] = { sel:46, min:0, max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };
这篇关于如何获得数组的键在Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!