js中for in和for of詳細講解

1、for in的詳細講解, for in遍歷數組的毛病

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

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

3.使用for in會遍歷數組[所有的可枚舉屬性]。
包括[原型]。例如上慄的[原型方法]method和[name]屬性

所以for in更適合遍歷對象,儘量不要使用for in遍歷數組。

for in中index索引爲字符串型數字

var myArray=[1,2,4,5,6,7]

myArray.name="name數組"
for (var index in myArray) {
    //這裏可以說明是字符串型數字
    console.log("字符串型數字===>", index +1)
    //也說明了會遍歷【可枚舉屬性】
    console.log(myArray[index]);
}

 

for in中會遍歷所有的可枚舉屬性

Object.prototype.say=function(){
  console.log('say');
}
var myObject={
  a:1,
  b:2,
  c:3
}

for (var key in myObject) {
    console.log('key值',key);
}

 

for in不遍歷原型屬性和原型方法

有些時候,不遍歷原型屬性和原型方法。
我們可以使用Object.hasOwnPropery(keyName)
hasOwnProperty()用於判斷一個對象自身(不包括原型鏈)是否具有指定的屬性。如果有,返回true,否則返回false。

Object.prototype.say=function(){
  console.log('say');
}
var myObject={
  name:'範輕舟',
  sex:'男',
  age:25
}
// 往對象上添加屬性
myObject.likes='寫代碼'
// 往對象上添加屬性
myObject['height']='1.80cm'
console.log(myObject )
for (var key in myObject) {
  if(myObject.hasOwnProperty(key)){
    console.log(key);
  }
}

獲取對象上的所有key值

通過ES5的Object.keys(myObject)
獲取[對象實例]【屬性】組成的數組,不包括原型方法和屬性

Object.prototype.say=function(){
  console.log('say');
}
var myObject={
  name:'範輕舟',
  sex:'男',
  age:25
}
let allkesy=Object.keys(myObject)
console.log( '獲取對象上的所有key值', allkesy)
輸出  ["name", "sex", "age"]

 

2、for-of遍歷數組對象

 

let arr=[ 
    {name:'張三',age:13},
    {name:'張三',age:13},
    {name:'張三',age:13}
]

for(let cont of arr){
    //輸出  {name:'張三',age:13},
    console.log(cont);
}

 

for-of遍歷字符串

let  strCont="你好啊!Javascript"
for (const item of strCont) {
    console.log(item);
}

 

for-of遍歷數組新增一個key值

let arr=[
    {name:'張三',age:13},
    {name:'張三',age:13},
    {name:'張三',age:13}
]

for(let cont of arr){
    cont['newkeys']=''
}

區別

1==》for in遍歷的是數組的索引(即鍵名)。
而for of遍歷的是數組元素值。

2==》for in 是es5中有的,for of是es6的

3==》for-in是爲遍歷對象而設計的,不適用於遍歷數組。
它可以正確響應break、continue和return語句
for-in遍歷數組的缺點:
因爲for-in遍歷的index值"0","1","2"等是字符串而不是數字
for-in循環存在缺陷:會遍歷對象自身的和繼承的可枚舉屬性(不含Symbol屬性)

3==》for-of這個方法避開了for-in循環的所有缺陷
適用遍歷數組對象/字符串/map/set等擁有迭代器對象的集合
它可以正確響應break、continue和return語句

最後一句話

for in遍歷對象
for of遍歷數組

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章