美文网首页
for-in和Object.keys对比

for-in和Object.keys对比

作者: 未路过 | 来源:发表于2022-10-21 16:56 被阅读0次
  1. for-in会遍历原型链上的属性,而且是可枚举的属性。
  2. Object.keys只会遍历自身的属性,而且是可枚举的属性。
  var sourceObj = {
        name: 'haha',
        age: 18,
        job: 'web',
        friends: ['f1', 'f2']
      }
      sourceObj.__proto__.test = 'test'

      Object.defineProperty(sourceObj, 'age', {
        enumerable: false
      })

      function cloneObj(sourceObj) {
        var targetObj = {}
        for (var prop in sourceObj) {
          targetObj[prop] = sourceObj[prop]
        }
        return targetObj
      }

      const newObj = cloneObj(sourceObj)
      console.log(newObj)//{name: 'haha', job: 'web', friends: Array(2), test: 'test'}

3.只遍历对象自身的属性,而不遍历继承于原型链上的属性,使用hasOwnProperty 方法过滤一下。

   var sourceObj = {
        name: 'haha',
        age: 18,
        job: 'web',
        friends: ['f1', 'f2']
      }
      sourceObj.__proto__.test = 'test'

      Object.defineProperty(sourceObj, 'age', {
        enumerable: false
      })

      function cloneObj(sourceObj) {
        var targetObj = {}
        for (var prop in sourceObj) {
          console.log(prop)
          if (sourceObj.hasOwnProperty(prop)) {
            targetObj[prop] = sourceObj[prop]
          }
        }
        return targetObj
      }

      const newObj = cloneObj(sourceObj)
      console.log(newObj)//{name: 'haha', job: 'web', friends: Array(2)}

Object.keys

      function clone2Obj(sourceObj) {
        var targetObj = {}
        Object.keys(sourceObj).forEach((item) => {
          console.log(item)
          targetObj[item] = sourceObj[item]
        })
        return targetObj
      }
      const newObj2 = clone2Obj(sourceObj)
      console.log(newObj2)
      //{name: 'haha', job: 'web', friends: Array(2)}

!!!浅拷贝不会拷贝enumerable为false的属性。

相关文章

  • for-in和Object.keys对比

    for-in会遍历原型链上的属性,而且是可枚举的属性。 Object.keys只会遍历自身的属性,而且是可枚举的属...

  • (三)swift支持的流程结构

    一、swift支持的流程结构 1、循环结构 2、选择结构 3、跟C语言对比 二、for-in和范围运算符 三、sw...

  • for-in 和 for-of

    先来看下结果1.for in 对数组(Array)的遍历 2.for in 对对象(Object)的遍历 3.fo...

  • Swift 5.1 (5) - 控制流

    控制流 For-In循环 使用for-in循环迭代数组 使用for-in循环迭代字典 使用for-in循环迭代数值...

  • for-in的使用

    对Range使用for-in 对string.characters使用for-in 对Array使用for-in ...

  • Swift4.2_控制流

    官网链接 For-In循环 ( For-In Loops) 使用for-in循环遍历序列,例如数组中的项、数字范围...

  • 浅析JavaScript语句中的for-in

    目录: for-in的概念 for-in的作用 如何实现for-in 三个详细例子 相关知识延伸 1.for-in...

  • for-of循环

    ES6为我们提供了for-in循环和for-Each循环还要强大 之前的for-in循环 for-of循环 遍历数...

  • For-in

    用for-in去遍历容器时 NSArray 是按照数组的index顺序遍历 NSDictionary 是通过遍历字...

  • Swift5.5学习笔记四:控制流(Control Flow)

    //一、for-in循环//可以使用for-in迭代数组、区间、字符串等序列//使用for-in迭代数组 //使用...

网友评论

      本文标题:for-in和Object.keys对比

      本文链接:https://www.haomeiwen.com/subject/rqcbzrtx.html