var example = {"prop1": "value1","prop2": [ "value2_0", "value2_1"],"prop3": {"prop3_1": "value3_1"}}
遍历其“属性”的错误方式:
function recursivelyIterateProperties(jsonObject) {for (var prop in Object.keys(example)) {console.log(prop);recursivelyIterateProperties(jsonObject[prop]);}}
var o = {a:1,b:2,c:3},a = [];o[Symbol.iterator] = function*(){var ok = Object.keys(this);i = 0;while (i < ok.length) yield this[ok[i++]];};for (var value of o) console.log(value);// or you can even do likea = [...o];console.log(a);
var obj = {a: "foo",b: "bar",c: "foobar"};
// We need to iterate the string keys (not the objects)for(var someKey in obj){// We check if this key exists in the objif (obj.hasOwnProperty(someKey)){// someKey is only the KEY (string)! Use it to get the obj:var myActualPropFromObj = obj[someKey]; // Since dynamic, use [] since the key isn't literally named "someKey"
// NOW you can treat it like an objvar shouldBeBar = myActualPropFromObj.b;}}
if (typeof obj === 'object' && obj !== null) {Object.keys(obj).forEach(key => {console.log("\n" + key + ": " + obj[key]);});}
// *** Explanation line by line ***
// Explaining the bellow line// It checks if obj is neither null nor undefined, which means it's safe to get its keys.// Otherwise it will give you a "TypeError: Cannot convert undefined or null to object" if obj is null or undefined.// NOTE 1: You can use Object.hasOwnProperty() instead of Object.keys(obj).length// NOTE 2: No need to check if obj is an array because it will work just fine.// NOTE 3: No need to check if obj is a string because it will not pass the 'if typeof obj is Object' statement.// NOTE 4: No need to check if Obj is undefined because it will not pass the 'if type obj is Object' statement either.if (typeof obj === 'object' && obj !== null) {
// Explaining the bellow line// Just like in the previous line, this returns an array with// all keys in obj (because if code execution got here, it means// obj has keys.)// Then just invoke built-in javascript forEach() to loop// over each key in returned array and calls a call back function// on each array element (key), using ES6 arrow function (=>)// Or you can just use a normal function ((key) { blah blah }).Object.keys(obj).forEach(key => {
// The bellow line prints out all keys with their// respective value in obj.// key comes from the returned array in Object.keys(obj)// obj[key] returns the value of key in objconsole.log("\n" + key + ": " + obj[key]);});}