为什么我的for-each循环没有在JavaScript关联数组对象上迭代?

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

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

推荐答案

.length属性仅跟踪具有数字索引(键)的属性.你用字符串作为键.

你可以这样做:

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

为安全起见,在这样的循环中,最好确保所有属性都不是意外的继承结果:

for (var key in arr_jq_TabContents) {
  if (arr_jq_TabContents.hasOwnProperty(key))
    console.log(arr_jq_TabContents[key]);
}

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);

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相关问答推荐

Math.random超出了最大调用堆栈

try 在addEventHandler内设置表单的文件输入.值=空

更改一组用户创建的项目的js排序标准

响应式JS DataTable中的Bootstrap 5弹出程序无法正常工作

从外部访问组件变量-Vueejs

如何通过继承contentitable属性的元素捕捉keydown事件?

vanillajs-datepicker未设置输入值,日期单击时未触发更改事件

具有相同参数的JS类

GrapeJS -如何保存和加载自定义页面

类型自定义lazy Promise. all

并不是所有的iframe都被更换

当id匹配时对属性值求和并使用JavaScript返回结果

当使用';字母而不是与';var#39;一起使用时,访问窗口为什么返回未定义的?

查询参数未在我的Next.js应用路由接口中定义

如何将数据块添加到d3力有向图中?

如何使用基于promise (非事件emits 器)的方法来传输数据?

MongoDB受困于太多的数据

第一项杀死下一项,直到数组长度在javascript中等于1

为什么我不能使用其同级元素调用和更新子元素?

在JavaScript中将Base64转换为JSON