for in和for of遍历显示的区别
- for in遍历对象的属性,包含原型链上的属性
- for of迭代对象自身的迭代值, 并不会显示属性值 ```typescript Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {};
let iterable = [3, 5, 7]; iterable.foo = ‘hello’;
// @1 可以显示多个属性,包括原型链上的 for (let i in iterable) { console.log(i); // 0, 1, 2, “foo”, “arrCustom”, “objCustom” }
//@2 通常需要配合hasOwnProperty使用 for (let i in iterable) { // 使用hasOwnProperty过滤掉非自身属性 if (iterable.hasOwnProperty(i)) { console.log(i, iterable[i]); // 0 3, 1 5, 2 7, “foo” hello } } //@3 仅仅显示自身上的属性 for (let i of iterable) { console.log(i); // 3, 5, 7 }
objCustom被挂载到Object对象原型链上,arrCustom被挂载到Array对象原型链。在@1执行for in遍历时,会把原型链上objCustom和arrCustom属性显示出来。通过使用hasOwnProperty可以过滤掉对象原型链上的属性,<br />所以在@2中只显示iterable对象自身的属性值0,1,2,foo。<a name="fpgJH"></a>## for in和for of迭代类型的区别**for in可以操作所有对象。**实际是变量对象属性的名称<br />for of**只能遍历有iterable属性对象的集合,包括Array、String、Arguments、Set、Map,基本对象Object不具有此特性。**```javascriptlet person = {name:"北鸟南游", age:12};for(let k in person){console.log(k, person[k]) // name 北鸟南游 age 12}for(let k of person){console.log(k, person[k]) // VM4458:1 Uncaught TypeError: person is not iterable}
iterable对的forEach方法
能使用for of进行迭代操作的对象,都可以使用forEach进行迭代操作。
Array数组
var arr = ['A', 'B', 'C'];arr.forEach(function (item, index, array) {// item: 指向当前元素的值// index: 指向当前索引// array: 指向Array对象本身alert(item);});
Set对象
var set = new Set(['A', 'B', 'C']);set.forEach(function (element, sameElement, set) {alert(element);});
Map对象
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);m.forEach(function (value, key, map) {alert(value);});
