Js中for in 和for of的區別

對數組的遍歷你們最經常使用的就是for循環,ES5的話也能夠使用forEach,ES5具備遍歷數組功能的還有map、filter、some、every、reduce、reduceRight等,只不過他們的返回結果不同。可是使用foreach遍歷數組的話,使用break不能中斷循環,使用return也不能返回到外層函數。數組

那麼接下來咱們一塊兒看一下for in 和for of 的區別吧。bash

for in

看一個簡單的例子函數

//for in 應用於數組
Array.prototype.sayHello = function(){
    console.log("Hello")
}
Array.prototype.str = 'world';
var myArray = [1,2,10,30,100];
myArray.name='數組';

for(let index in myArray){
    console.log(index);
}
//輸出結果以下
0,1,2,3,4,name,str,sayHello

//for in  應用於對象中
Object.prototype.sayHello = function(){
    console.log('Hello');
}
Obeject.prototype.str = 'World';
var myObject = {name:'zhangsan',age:100};

for(let index in myObject){
    console.log(index);
}
//輸出結果
name,age,str,sayHello
//首先輸出的是對象的屬性名,再是對象原型中的屬性和方法,
//若是不想讓其輸出原型中的屬性和方法,能夠使用hasOwnProperty方法進行過濾
for(let index in myObject){
    if(myObject.hasOwnProperty(index)){
        console.log(index)
    }
}
//輸出結果爲
name,age
//你也能夠用Object.keys()方法獲取全部的自身可枚舉屬性組成的數組。
Object.keys(myObject)

複製代碼

能夠看出for in 應用於數組循環返回的是數組的下標和數組的屬性和原型上的方法和屬性,而for in應用於對象循環返回的是對象的屬性名和原型中的方法和屬性。ui

使用for in 也能夠遍歷數組,可是會存在如下問題:spa

1.index索引爲字符串型數字,不能直接進行幾何運算prototype

2.遍歷順序有可能不是按照實際數組的內部順序code

3.使用for in會遍歷數組全部的可枚舉屬性,包括原型。例如上慄的原型方法method和name屬性對象

for of
Object.prototype.sayHello = function(){
    console.log('Hello');
}
var myObject = {
    name:'zhangsan',
    age:10
}

for(let key of myObject){
    consoloe.log(key);
}
//輸出結果
//typeError

Array.prototype.sayHello = function(){
    console.log("Hello");
}
var myArray = [1,200,3,400,100];
for(let key of myArray){
    console.log(key);
}
//輸出結果
1,200,3,400,100

複製代碼

for in遍歷的是數組的索引(即鍵名),而for of遍歷的是數組元素值。 因此for in更適合遍歷對象,不要使用for in遍歷數組。索引

相關文章
相關標籤/搜索