为什么我的for- 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]);
}

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


当前回答

这是一个非常简单的方法。好处是你也可以得到钥匙:

for (var key in array) {
    var value = array[key];
    console.log(key, value);
}

For ES6:

array.forEach(value => {
  console.log(value)
})

对于ES6(如果你想要值,索引和数组本身):

array.forEach((value, index, self) => {
  console.log(value, index, self)
})

其他回答

已经有一些简单的例子了,但是我注意到你的问题的措辞表明你可能有PHP的背景,你希望JavaScript也能以同样的方式工作——事实并非如此。PHP数组与JavaScript数组非常不同。

在PHP中,关联数组可以完成数值索引数组所能做的大部分工作(array_*函数可以工作,您可以count()它,等等)。您只需创建一个数组并开始分配字符串索引,而不是数值索引。

In JavaScript, everything is an object (except for primitives: string, numeric, boolean), and arrays are a certain implementation that lets you have numeric indexes. Anything pushed to an array will affect its length, and can be iterated over using Array methods (map, forEach, reduce, filter, find, etc.) However, because everything is an object, you're always free to simply assign properties, because that's something you do to any object. Square-bracket notation is simply another way to access a property, so in your case:

array['Main'] = 'Main Page';

实际上相当于:

array.Main = 'Main Page';

From your description, my guess is that you want an 'associative array', but for JavaScript, this is a simple case of using an object as a hashmap. Also, I know it's an example, but avoid non-meaningful names that only describe the variable type (e.g. array), and name based on what it should contain (e.g. pages). Simple objects don't have many good direct ways to iterate, so often we'll turn then into arrays first using Object methods (Object.keys in this case -- there's also entries and values being added to some browsers right now) which we can loop.

// Assigning values to corresponding keys
const pages = {
  Main: 'Main page',
  Guide: 'Guide page',
  Articles: 'Articles page',
  Forum: 'Forum board',
};

Object.keys(pages).forEach((page) => console.log(page));

arr_jq_TabContents[key]将数组视为0索引形式。

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 -现在注意Object.keys()函数在现代浏览器和Node等中可用可能是个好主意。该函数返回对象的“自己的”键,作为数组:

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

这在大多数情况下(本质上)是不正确的:

var array = [];
array["Main"] = "Main page";

这将在名为Main的数组上创建一个非元素属性。虽然数组是对象,但通常不希望在数组上创建非元素属性。

如果你想通过这些名称索引到数组中,通常你会使用Map或普通对象,而不是数组。

用一个地图(ES2015+),我称之为地图,因为我很有创意:

let map = new Map();
map.set("Main", "Main page");

然后使用它的值、键或入口方法中的迭代器迭代它,例如:

for (const value of map.values()) {
    // Here, `value` will be `"Main page"`, etc.
}

使用一个普通对象,我创造性地称之为obj:

let obj = Object.create(null); // Creates an object with no prototype
obj.Main = "Main page"; // Or: `obj["Main"] = "Main page";`

然后使用Object迭代它的内容。钥匙,对象。values,或Object。条目,例如:

for (const value of Object.values(proches_X)) {
    // Here, `value` will be `"Main page"`, etc.
}

你可以这样做:

var array = [];

// Assigning values to corresponding keys
array[0] = "Main page";
array[1] = "Guide page";
array[2] = "Articles page";
array[3] = "Forum board";


array.forEach(value => {
    console.log(value)
})