为什么我的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/


当前回答

下面是一个使用关联数组作为泛型对象类型的简单方法:

Object.prototype.forEach =函数(cb){ if(this instanceof Array)返回this. foreach (cb); Let self = this; Object.getOwnPropertyNames(这).forEach ( (k) = > {cb。调用(self, self[k], k);} ); }; 对象({1,b: 2, c: 3})。forEach((值,键)= > { Console.log('键/值对:${键}/${值}'); });

其他回答

下面是一个使用关联数组作为泛型对象类型的简单方法:

Object.prototype.forEach =函数(cb){ if(this instanceof Array)返回this. foreach (cb); Let self = this; Object.getOwnPropertyNames(这).forEach ( (k) = > {cb。调用(self, self[k], k);} ); }; 对象({1,b: 2, c: 3})。forEach((值,键)= > { Console.log('键/值对:${键}/${值}'); });

似乎几乎每一个答案都不是一开始问的。

foreach-loop似乎不起作用。简单的for循环也不能很好地工作,因为length属性在关联数组的情况下将为零(这是一种退步)。而for-in则用于关联数组

//定义数组 Var数组= []; //为相应的键赋值 array["Main"] = "主页"; array["Guide"] = "指南页"; array["Articles"] = "Articles page"; array["论坛"]= "论坛板"; //期望:遍历每一项, //但它只记录“最后”分配的值-“论坛” 对于(var index in array) { console.log(索引数组(指数)); }

已经有一些简单的例子了,但是我注意到你的问题的措辞表明你可能有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));

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

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

如果Node.js或浏览器支持Object.entries(),它可以用作Object.keys()的替代方案(Pointy的答案)。

Const h = { 答:1, b: 2 }; Object.entries (h)。forEach(([key, value]) => console.log(value)); // log 1, 2

在这个例子中,forEach使用数组的解构赋值。