关于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遍历数组的值
发布了30 篇原创文章 · 获赞 9 · 访问量 2503

猜你喜欢

转载自blog.csdn.net/weixin_42446516/article/details/103457136
今日推荐