关联数组对象上的 JavaScript foreach 循环 [英] JavaScript foreach loop on an associative array object

查看:50
本文介绍了关联数组对象上的 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]);
}

编辑 —现在注意到 Object.keys() 函数在现代浏览器和 Node 等中可用可能是个好主意.该函数返回对象的自己的"键,作为数组:

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() — 来完成的.原始对象—它将在回调中绑定为 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 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆