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

本文翻译自:For..In loops in JavaScript - key value pairs

I was wondering if there's a way to do something like a PHP foreach loop in JavaScript. 我想知道是否有办法在JavaScript中执行类似PHP foreach循环的操作。 The functionality I'm looking for is something like this PHP Snippet: 我正在寻找的功能就像这个PHP代码片段:

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

I was looking at the JS for..in loop, but there seems to be no way to specify the as . 我正在查看JS for..in循环,但似乎没有办法指定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? 如果我使用' for(var i = 0; i < data.length; i++循环( for(var i = 0; i < data.length; i++ )),有没有办法获取key => value对?


#1楼

参考:https://stackoom.com/question/UNwU/For-In循环中的JavaScript-键值对


#2楼

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. 在javascript中,每个对象都有一堆具有元信息的内置键值对。 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. 使用hasOwnProperty()过滤掉这些。


#3楼

ES6 will provide Map.prototype.forEach(callback) which can be used like this ES6将提供Map.prototype.forEach(回调),可以像这样使用

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

#4楼

If you can use ES6 natively or with Babel (js compiler) then you could do the following: 如果您可以本机使用ES6或使用Babel (js编译器),那么您可以执行以下操作:

 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...in loop (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! 希望能帮助到你! =) =)


#5楼

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

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

#6楼

If you are using Lodash , you can use _.forEach 如果您使用的是Lodash ,则可以使用_.forEach

_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  console.log(key + ": " + value);
});
// => Logs 'a: 1' then 'b: 2' (iteration order is not guaranteed).
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值