JavaScript 中的 For..In 循环 - 键值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7241878/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:27:30  来源:igfitidea点击:

For..In loops in JavaScript - key value pairs

javascriptforeach

提问by cabaret

I was wondering if there's a way to do something like a PHP foreachloop in JavaScript. The functionality I'm looking for is something like this PHP Snippet:

我想知道是否有办法foreach在 JavaScript 中执行类似 PHP循环的操作。我正在寻找的功能类似于这个 PHP Snippet:

foreach($data as $key => $value) { }

I was looking at the JS for..inloop, but there seems to be no way to specify the as. If I do this with a 'normal' for loop (for(var i = 0; i < data.length; i++), is there a way to grab the key => value pairs?

我正在查看 JSfor..in循环,但似乎无法指定as. 如果我使用“正常” for 循环 ( for(var i = 0; i < data.length; i++)执行此操作,有没有办法获取键 => 值对?

采纳答案by Francesco Casula

If you can use ES6natively or with Babel(js compiler) then you could do the following:

如果您可以在本机或Babel(js 编译器)中使用ES6,那么您可以执行以下操作:

const test = {a: 1, b: 2, c: 3};

for (const [key, value] of Object.entries(test)) {
  console.log(key, value);
}

Which will print out this output:

这将打印出此输出:

a 1
b 2
c 3

The Object.entries()method returns an array of a given object's own enumerable property [key, value]pairs, in the same order as that provided by a for...inloop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Object.entries()方法返回给定对象自己的可枚举属性[key, value]对的数组,其顺序与for...in循环提供的顺序相同(区别在于 for-in 循环也枚举原型链中的属性)

Hope it helps! =)

希望能帮助到你!=)

回答by J0HN

for (var k in target){
    if (target.hasOwnProperty(k)) {
         alert("Key is " + k + ", value is " + target[k]);
    }
}

hasOwnPropertyis used to check if your targetreally has that property, rather than having inherited it from its prototype. A bit simpler would be:

hasOwnProperty用于检查您是否target真的拥有该属性,而不是从其原型中继承它。更简单一点的是:

for (var k in target){
    if (typeof target[k] !== 'function') {
         alert("Key is " + k + ", value is" + target[k]);
    }
}

It just checks that kis not a method (as if targetis arrayyou'll get a lot of methods alerted, e.g. indexOf, push, pop,etc.)

它仅仅检查k是不是方法(好像targetarray,你会得到很多的方法提醒,如indexOfpushpop,等。)

回答by goatslacker

No one has mentioned Object.keysso I'll mention it.

没有人提到,Object.keys所以我会提到它。

Object.keys(obj).forEach(function (key) {
   // do something with obj[key]
});

回答by Paul

for...inwill work for you.

因为...in会为你工作。

for( var key in obj ) {
  var value = obj[key];
}

In modern JavaScript you can also do this:

在现代 JavaScript 中,您还可以这样做:

for ( const [key,value] of Object.entries( obj ) ) {

}

回答by Zirak

var obj = {...};
for (var key in obj) {
    var value = obj[key];

}

The php syntax is just sugar.

php 语法只是糖。

回答by Felix Kling

I assume you know that iis the key and that you can get the value via data[i](and just want a shortcut for this).

我假设您知道这i是关键,并且您可以通过data[i](并且只想要一个快捷方式)获得价值。

ECMAScript5 introduced forEach[MDN]for arrays (it seems you have an array):

ECMAScript5为数组引入了forEach[MDN](看来你有一个数组):

data.forEach(function(value, index) {

});

The MDN documentation provides a shim for browsers not supporting it.

MDN 文档为不支持它的浏览器提供了一个 shim。

Of course this does not work for objects, but you can create a similar function for them:

当然,这不适用于对象,但您可以为它们创建类似的函数:

function forEach(object, callback) {
    for(var prop in object) {
        if(object.hasOwnProperty(prop)) {
            callback(prop, object[prop]);
        }
    }
}

Since you tagged the question with jquery, jQuery provides $.each[docs]which loops over both, array and object structures.

由于您使用jquery标记了问题,jQuery 提供了$.each[docs]来循环遍历数组和对象结构。

回答by Christoph Winkler

You can use the for..infor that.

您可以for..in为此使用。

for (var key in data)
{
    var value = data[key];
}

回答by Siddhu

for (var key in myMap) {
    if (myMap.hasOwnProperty(key)) {
        console.log("key =" + key);
        console.log("value =" + myMap[key]);
    }
}

In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. The use of hasOwnProperty() filters these out.

在 javascript 中,每个对象都有一堆具有元信息的内置键值对。当您遍历对象的所有键值对时,您也在遍历它们。使用 hasOwnProperty() 过滤掉这些。

回答by Stephen Murby

ES6 will provide Map.prototype.forEach(callback) which can be used like this

ES6 将提供 Map.prototype.forEach(callback) 可以像这样使用

myMap.forEach(function(value, key, myMap) {
                        // Do something
                    });

回答by u4751247

let test = {a: 1, b: 2, c: 3};
Object.entries(test).forEach(([key, value]) => console.log(key, value))

// a 1
// b 2
// c 3