javascript 关联数组对象上的Javascript foreach循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18804592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript foreach loop on associative array object
提问by Szymon Toda
Why my for for-each loop is not iterating over my JavaScript associative array object?
为什么我的 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]);
}
EDIT: jQuery each()
could be helpful: https://api.jquery.com/jQuery.each/
编辑:jQueryeach()
可能会有所帮助:https: //api.jquery.com/jQuery.each/
回答by Pointy
The .length
property only tracks properties with numeric indexes (keys). You're using strings for keys.
该.length
属性仅跟踪具有数字索引(键)的属性。您正在使用字符串作为键。
You can do this:
你可以这样做:
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— 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()
函数在现代浏览器和 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.)
传递给的回调函数.forEach()
使用每个键和键在返回的数组中的索引调用Object.keys()
。它还传递了函数迭代的数组,但该数组对我们来说并没有什么用;我们需要原始对象。这可以通过名称直接访问,但是(在我看来)显式传递它会更好一些,这是通过将第二个参数传递给.forEach()
原始对象来完成的,原始对象将this
在回调中绑定。(刚刚看到在下面的评论中指出了这一点。)
回答by tika
This is very simple approach. The Advantage is you can get keys as well:
这是非常简单的方法。优点是您也可以获得钥匙:
for (var key in array) {
var value = array[key];
console.log(key, value);
}
For ES6:
对于 ES6:
array.forEach(value => {
console.log(value)
})
For ES6: (If you want value, index and the array itself)
对于 ES6:(如果你想要值、索引和数组本身)
array.forEach((value, index, self) => {
console.log(value, index, self)
})
回答by Josh from Qaribou
There are some straightforward examples already, but I notice from how you've worded your question that you probably come from a PHP background, and you're expecting JavaScript to work the same way -- it does not. A PHP array
is very different from a JavaScript Array
.
已经有一些简单的例子,但我从你的问题措辞中注意到你可能来自 PHP 背景,并且你期望 JavaScript 以相同的方式工作 - 事实并非如此。PHParray
与 JavaScript 非常不同Array
。
In PHP, an associative array can do most of what a numerically-indexed array can (the array_*
functions work, you can count()
it, etc.) You simply create an array and start assigning to string-indexes instead of numeric.
在 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 effect 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:
在 JavaScript 中,一切都是对象(原始类型除外:字符串、数字、布尔值),数组是一种特定的实现,可以让您拥有数字索引。任何推送到数组的内容都会影响它的length
,并且可以使用 Array 方法(map
, forEach
, reduce
, filter
,find
等)进行迭代。但是,因为一切都是对象,所以您总是可以自由地简单地分配属性,因为这是您所做的任何对象。方括号表示法只是访问属性的另一种方式,因此在您的情况下:
array['Main'] = 'Main Page';
is actually equivalent to:
实际上相当于:
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.
根据您的描述,我的猜测是您想要一个“关联数组”,但对于 JavaScript,这是使用对象作为哈希图的简单情况。另外,我知道这是一个例子,但避免只描述变量类型的无意义名称(例如array
),以及基于它应该包含的内容(例如pages
)的名称。简单的对象不具有许多良好的直接方式来迭代,所以往往我们将把然后进入第一使用数组Object
的方法(Object.keys
在这种情况下-有也entries
和values
被添加到一些浏览器现在),我们可以循环。
// 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));
回答by MSO
arr_jq_TabContents[key]
sees the array as an 0-index form.
arr_jq_TabContents[key]
将数组视为 0 索引形式。
回答by Chouettou
Here is a simple way to use an associative array as a generic Object type:
这是使用关联数组作为通用对象类型的简单方法:
Object.prototype.forEach = function(cb){
if(this instanceof Array) return this.forEach(cb);
let self = this;
Object.getOwnPropertyNames(this).forEach(
(k)=>{ cb.call(self, self[k], k); }
);
};
Object({a:1,b:2,c:3}).forEach((value, key)=>{
console.log(`key/value pair: ${key}/${value}`);
});
回答by banyan
If the node.js or browser supported Object.entries()
, it can be used as an alternative to using Object.keys()
(https://stackoverflow.com/a/18804596/225291).
如果 node.js 或浏览器支持Object.entries()
,它可以作为替代使用Object.keys()
(https://stackoverflow.com/a/18804596/225291)。
const h = {
a: 1,
b: 2
};
Object.entries(h).forEach(([key, value]) => console.log(value));
// logs 1, 2
in this example, forEach
uses Destructuring assignmentof an array.
在本例中,forEach
使用数组的解构赋值。
回答by T.J. Crowder
This is (essentially) incorrect in most cases:
在大多数情况下,这(基本上)是不正确的:
var array = [];
array["Main"] = "Main page";
That creates a non-element property on the array with the name Main
. Although arrays are objects, normally you don't want to create non-element properties on them.
这会在名称为 的数组上创建一个非元素属性Main
。尽管数组是对象,但通常您不想在它们上创建非元素属性。
If you want to index into array
by those names, typically you'd use a Map
or a plain object, not an array.
如果要按array
这些名称进行索引,通常会使用 aMap
或普通对象,而不是数组。
With a Map
(ES2015+), which I'll call map
because I'm creative:
使用Map
(ES2015+),map
因为我很有创意,所以我称之为:
let map = new Map();
map.set("Main", "Main page");
you then iterate it using the iterators from its values
, keys
, or entries
methods, for instance:
你再使用从它的迭代器遍历它values
,keys
或entries
方法,例如:
for (const value of map.values()) {
// Here, `value` will be `"Main page"`, etc.
}
Using a plain object, which I'll creatively call obj
:
使用一个普通对象,我将创造性地称之为obj
:
let obj = Object.create(null); // Creates an object with no prototype
obj.Main = "Main page"; // Or: `obj["Main"] = "Main page";`
you'd then iterate its contents using Object.keys
, Object.values
, or Object.entries
, for instance:
然后你会使用迭代的内容Object.keys
,Object.values
或者Object.entries
,如:
for (const value of Object.values(proches_X)) {
// Here, `value` will be `"Main page"`, etc.
}
回答by Shuvro
You can Do this
你可以这样做
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)
})
回答by Dev-Wb Ahmed
var obj = {
no: ["no", 32],
nt: ["no", 32],
nf: ["no", 32, 90]
};
count = -1; // which must be static value
for (i in obj) {
count++;
if (obj.hasOwnProperty(i)) {
console.log(obj[i][count])
};
};
in this code i used brackets method for call values in array because it contained array , however briefly the idea which a variable i has a key of property and with a loop called both values of associate array
在这段代码中,我使用括号方法调用数组中的值,因为它包含数组,但简单地说,我的变量具有属性键和循环调用关联数组的两个值的想法
perfect Method , if you interested, press like
完美的方法,有兴趣的可以点赞