練習問題として、JSオブジェクトのキーと値を印刷する方法を学びたいと考えています。私は苦労している。JavaScriptオブジェクトを反復できない
0 : J
1 : o
2 : h
3 : n
0 : 1
1 : 0
2 :/
3 : 1
4 : 8
5 :/
6 : 2
7 : 0
8 : 0
9 : 8
0 : 2
0 : w
1 : w
2 : w
3 : .
4 : s
5 : a
6 : m
7 : p
8 : l
9 : e
10 : w
11 : e
12 : b
13 : s
14 : i
15 : t
16 : e
17 : .
18 : c
19 : o
20 : m
Iを次のように
は、以下の、バージョン1とバージョン2のプリントと同じ出力私が書いた基本的なオブジェクトであると指摘したようにちょうどkey : value
var obTest = {
name: "John",
WeddingDate: "10/18/2008",
NumberKids: "2",
Website: "www.samplewebsite.com
};
/* VERSION 1
for (var key in obTest) {
// skip loop if the property is from prototype
if (!obTest.hasOwnProperty(key)) continue;
var obKey = obTest[key];
for (var obProp in obKey) {
// skip loop if the obProperty is from prototype
if(!obKey.hasOwnProperty(obProp)) continue;
// your code
alert(obProp + " : " + obKey[obProp]);
}
};
// note: this prints each character as a key:value
*/
/* VERSION 2
for (var key in obTest) {
if (obTest.hasOwnProperty(key)) {
var obKey = obTest[key];
for (var prop in obKey) {
if (obKey.hasOwnProperty(prop)) {
console.log(prop + " : " + obKey[prop]);
}
}
}
};
// note: this prints each character as a key:value
*/
// VERSION 3
Object.keys(obTest.forEach(function(key) {
console.log(key, obTest[key]);
}));
// note: this gives me a breakpoint and can't figure out why it does not work
を印刷したいですVisual Studioコードをバージョン3に使用してブレークポイントを取得してください。
name : John
WeddingDate : 10/18/2008
NumberKids : 2
Website : www.samplewebsite.com
私は数字キー、特に自分自身を繰り返しているものは持ちたくありません。私が読んだ他の記事は意味をなさないようです。 Pythonは、オブジェクトのキーと値を反復して出力することはとても簡単です。
ありがとうございました! 、あなたの第二のループで
for (var key in obTest) {
// skip loop if the property is from prototype
if (!obTest.hasOwnProperty(key)) continue;
//find the object corresponding to the current key
var obKey = obTest[key];
//output the key and the corresponding object
alert(key + " : " + obKey);
};
を、あなたはすべてのペア「のキー:値」列挙する:
'forEach'は、' obTest.hasOwnProperty'など独自のプロパティを持つオブジェクトをスキップしない私のためにそれを –