本文翻译自: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循环枚举原型链中的属性也是如此) 。
- Object.entries documentation Object.entries文档
- for...of documentation 为......文件
- Destructuring assignment documentation 解构分配文档
- Enumerability and ownership of properties documentation 属性文档的可插入性和所有权
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).
本文探讨了在JavaScript中如何遍历对象的键值对,提供了多种方法,包括使用for...in循环、ES6的Map.prototype.forEach、Object.entries以及Lodash的_.forEach等,旨在帮助开发者更高效地处理键值对数据。
556

被折叠的 条评论
为什么被折叠?



