对关联数组对象中的JavaScript foreach循环 [英] Javascript foreach loop on associative array object
问题描述
为什么我的for-each循环不遍历我的JavaScript关联数组对象?
Why my for for-each loop is not iterating over my JavaScript associative array object?
// defining an array
var array = [];
// assigning values to corresponding keys
array["Main"] = "Main page";
array["Guide"] = "Guide page";
array["Articles"] = "Articles page";
array["Forum"] = "Forum board";
// expected: loop over every item,
// yet it logs only "last" assigned value - "Forum"
for (var i = 0; i < array.length; i++) {
console.log(i);
}
编辑:jQuery的每()
可能会有所帮助:的https:/ /api.jquery.com/jQuery.each/
推荐答案
的。长度
属性只跟踪性能与数字索引(键)。您使用字符串键。
The .length
property only tracks properties with numeric indexes (keys). You're using strings for keys.
您可以这样做:
var arr_jq_TabContents = {}; // no need for an array
arr_jq_TabContents["Main"] = jq_TabContents_Mian;
arr_jq_TabContents["Guide"] = jq_TabContents_Guide;
arr_jq_TabContents["Articles"] = jq_TabContents_Articles;
arr_jq_TabContents["Forum"] = jq_TabContents_Forum;
for (var key in arr_jq_TabContents) {
console.log(arr_jq_TabContents[key]);
}
为了安全起见,它在这样的循环是一个好主意,以确保没有任何属性都继承意想不到的结果:
To be safe, it's a good idea in loops like that to make sure that none of the properties are unexpected results of inheritance:
for (var key in arr_jq_TabContents) {
if (arr_jq_TabContents.hasOwnProperty(key))
console.log(arr_jq_TabContents[key]);
}
的修改的&MDASH;它可能是一个好主意,现在要注意的是, Object.keys()
功能在现代浏览器和节点等。该函数返回一个对象的自己的钥匙作为一个数组:
edit — it's probably a good idea now to note that the Object.keys()
function is available on modern browsers and in Node etc. That function returns the "own" keys of an object, as an array:
Object.keys(arr_jq_TabContents).forEach(function(key, index) {
console.log(this[key]);
}, arr_jq_TabContents);
传递给 .forEach()
被称为与每个键和返回的数组中的关键指数Object.keys(回调函数)
。它也通过了,通过该功能遍历数组,但数组不是我们真正有用的;我们需要原始的对象的。可以直接通过名称来访问,但(在我看来)这是一个更好一点,以通过传递第二个参数 .forEach()显式地传递,这是做
&MDASH ;原始物体MDASH;这将回调内部的约束这个
。 (刚看到,这是在下面的注释说明。)
The callback function passed to .forEach()
is called with each key and the key's index in the array returned by Object.keys()
. It's also passed the array through which the function is iterating, but that array is not really useful to us; we need the original object. That can be accessed directly by name, but (in my opinion) it's a little nicer to pass it explicitly, which is done by passing a second argument to .forEach()
— the original object — which will be bound as this
inside the callback. (Just saw that this was noted in a comment below.)
这篇关于对关联数组对象中的JavaScript foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!