本文介绍了关联数组对象上的JavaScript foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么for-each循环不遍历我的JavaScript关联数组对象?

Why is my for for-each loop 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(array[i]);
}

jQuery each()可能会有所帮助: https://api.jquery.com/jQuery.each/

jQuery each() could be helpful: https://api.jquery.com/jQuery.each/

推荐答案

.length 属性仅跟踪带有数字索引(键)的属性.您正在使用字符串作为键.

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_Main;
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]);
}

edit —现在可能要注意一个好主意,在现代浏览器和Node等中都可以使用 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()返回的数组中键的索引调用.它也传递了函数在其中进行迭代的数组,但是该数组对我们而言并没有真正的用处.我们需要原始的 object .可以直接通过名称访问,但是(在我看来)显式传递它要好一些,这是通过将第二个参数传递给 .forEach()—来完成的.原始对象—它将在回调中绑定为 this .(刚刚在下面的评论中注意到了这一点.)

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循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:22