关于数组/对象的遍历 for in for of

        let arr = [3, 4, 5]
        let obj = {
            "a": "val_a",
            "b": "val_b",
            "c": "val_c"
        }

        for (let i in arr) {
            console.log(i); // 0 1 2
        }
        for (let i of arr) {
            console.log(i); // 3 4 5
        }
        for (let i in obj) {
            console.log(i); // a b c
        }
        for (let i of obj) {
            console.log(i); // Uncaught TypeError: obj is not iterable
        }
        console.log(Object.keys(obj)); // ['a', 'b', 'c']
        console.log(Object.values(obj)); // ["val_a", "val_b", "val_c"]
	Object.prototype.objCustom = function() {}; 
	Array.prototype.arrCustom = function() {};
	
	let iterable = [3, 5, 7];
	iterable.foo = 'hello';
	
	for (let i in iterable) {
	  console.log(i); // 0, 1, 2, "foo", "arrCustom", "objCustom"
	}
	
	for (let i in iterable) {
	  if (iterable.hasOwnProperty(i)) {
	    console.log(i); // 0, 1, 2, "foo"
	  }
	}
	
	for (let i of iterable) {
	  console.log(i); // 3, 5, 7
	}
  • for…in 遍历的是可枚举的属性(索引),for…of 遍历的是值
  • for…in 是为遍历对象属性而构建的,不建议与数组一起使用
  • for…of为什么不能遍历对象

你可能感兴趣的:(javascript)