關於for...of for..in和Object.keys()的相同,不同之處

         // 一: 遍歷對象的方法
        let person = { name: "張三", age: 25, address: "深圳", getName: function () { } }
         Object.keys(person).map((key) => {
            console.log(person[key]) // 獲取到屬性對應的值,做一些處理
        }) 
        // 效果是一樣的 打印的結果是  張三 25 深圳 f(){}
        for(key in person){
          console.log(person[key])
        }


       // 二:關於Object.keys()和for...in的不同之處對象定義屬性的方法
        Object.defineProperty(Object.prototype, 'mynames',{
            configurable: true, // 可配置的
            enumerable: true, // 
            writable: true, // 可寫的
            value: 'my name is ting'
        })
        let obj = {
            age: 26,
            sex: '女',
            fn: function () {

            }
        }
        for(let key in obj){
            console.log(key) // age sex fn mynames
            console.log(obj[key]) // 26  女   f(){}   my name is ting
        }
        console.log(Object.keys(obj)) // ["age", "sex", "fn"]
       // 結果: for...in 會枚舉對象原型上的可枚舉屬性,而Object.keys()不會


        //三: for...of 和 for...in的不同
         try{
           for(let key of obj){
              console.log(key) // obj is not iterable
            }
           } catch(err){  
           }
        for(let key of Object.keys(obj)){
          console.log(key) // age sex fn 
          console.log(obj[key]) // 26 女 f(){}
        }
       // 結果for....of不能遍歷對象,但是可以遍歷Object.keys()之後的數組


       // 四: for...of 遍歷數組 
        let arr = [1, 2, 3, 4, 5]
          arr.forEach((item, index) => {
            console.log(item, index) // 可以遍歷
          })

          for(let key in arr){
            console.log(arr[key], key) // 可以,但key值是字符的“”
          }
        
          for(let key of arr){
            console.log(arr[key], key) // 不可以
          }

          for(let key of Object.keys(arr)){
            console.log(arr[key]) // 可以
         }

        for(let key of arr){
            console.log(key) //可以 1 2 3 4 5
        }

        //結果for...of遍歷數組時 返回的key遍歷數組的值
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章