首页 > 解决方案 > 来自对象数组的javascript深拷贝成员

问题描述

我有一个对象数组,看起来像

[
  {Time: , //time stamp 
   psi:  //pressure value at the time
  }, 
  ... //other objects in the array the same
]

该数组被命名为“数据”

如果我对数组的一部分进行切片,并将它们传递给查找局部最大值和最小值,那么下面的代码是否会深度复制并返回局部极值?如何验证?

var extreme = findLocalExtreme(data.slice(0, 10));  //slice(0, 10) for example, shallow copy

function findLocalExtreme(slicedArr){
  //error control skipped, the array could be empty or only 1 member
  let tempMax = slicedArr[0]; //would the "=" deep copy the object or just shallow copy? 
  let tempMin = slicedArr[0];
  let slicedArrLength = slicedArr.length;
  for (let i = 1; i < slicedArrLength; i++){
    if (slicedArr[i].psi > tempMax.psi){
      tempMax = slicedArr[I]; //deep copy or shallow copy?
    }
    if (slicedArr[i].psi < tempMin.psi){
      tempMin = slicedArr[i];
    }
  }
  return {
    Max: tempMax, 
    Min: tempMin //is the value assignment in returned class deep copy, or still shallow copy?
  }
}

欢迎任何建议。

标签: javascriptarraysjsonjavascript-objects

解决方案


let tempMax = slicedArr[0] 只会做浅拷贝而不是你可以做 的, let tempMax = {...slicedArr[0]} 因为你的对象只在一级,这将做一个深拷贝,如果它是嵌套的,你可以使用 loadash 的 cloneDeep 做一个深拷贝。

将对象分配给变量的任何地方都是浅拷贝


推荐阅读