for in
for…in语句以任意顺序迭代一个对象的除Symbol以外的可枚举属性,包括继承的可枚举属性。
for … in是为遍历对象属性而构建的,不建议与数组一起使用
var obj = {a:1, b:2, c:3};for (var prop in obj) {console.log( prop);}//a,b,c
仅迭代自身的属性
如果你只要考虑对象本身的属性,而不是它的原型,那么使用 getOwnPropertyNames() 或执行 hasOwnProperty() 来确定某属性是否是对象本身的属性
var triangle = {a: 1, b: 2, c: 3};function ColoredTriangle() {this.color = 'red';}ColoredTriangle.prototype = triangle;var obj = new ColoredTriangle();for (var prop in obj) {if (obj.hasOwnProperty(prop)) {console.log(prop);}}//这里就仅输出了 ColoredTriangle 自身的属性// color//这里就仅输出了 ColoredTriangle 自身的属性console.log(Object.getOwnPropertyNames(obj))//['color']
for of
for…of语句用于循环可迭代对象(Array,Map,Set,String,arguments,nodeList,HTMLCollection 等等)
//迭代字符串let iterable = "boo";for (let value of iterable) {console.log(value);}// "b"// "o"// "o"//迭代Maplet iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);for (let entry of iterable) {console.log(entry);}// ["a", 1]// ["b", 2]// ["c", 3]//迭代 argumentsfunction test(){for (let argument of arguments) {console.log(argument);}}test(1,2,3,4,5)//1//2//3//4//5//迭代 DOM 集合let nodeList = document.querySelectorAll('li')for(node of nodeList){console.log(node)}// <li></li>// ......
两者区别
for … in是为遍历对象属性而构建的,不要用它去遍历数组 。for…in 语句以任意顺序迭代对象的可枚举属性。
for…of 语句遍历可迭代对象定义要迭代的数据
部分具体差异如下:
Object.prototype.objCustom = function() {};Array.prototype.arrCustom = function() {};let iterable = [3, 5, 7];iterable.foo = 'hello';for (let i in iterable) {console.log(i); //打印得是key}for (let i in iterable) {console.log(iterable[i]); //打印得是value}// 0, 1, 2, "foo", "arrCustom", "objCustom" //key// 3, 5, 7, hello, ƒ () {}, ƒ () {} //valuefor(let i of iterable){console.log(i)}// 3 5 7
重要;虽然for … in 也能循环字符串/arguments/NodeList等等。但我们最好不用这个来循环数组/类数组。仅用作循环对象。
