本文翻譯自: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).