简体   繁体   English

克隆javascript对象属性?

[英]Clone javascript object attributes?

Lets say I have several objects. 可以说我有几个对象。 These objects have four properties each, containing simple integers. 这些对象每个都有四个属性,其中包含简单的整数。 I want to create another object with the highest values for each property, so its a chimeric object. 我想为每个属性创建另一个具有最高值的对象,因此它是一个嵌合对象。 I don't want it to change the originals when I manipulate it and vice versa. 当我操作它时,我不希望它改变原件,反之亦然。

Whats the way to do this in javascript? 用JavaScript执行此操作的方法是什么? A simple assignment would create a reference, but I need a duplicate. 一个简单的任务将创建一个引用,但是我需要一个副本。

PS: Pure JS please, no libraries. PS:请使用纯JS,没有库。

It sounds like you are trying to do something like this. 听起来您正在尝试做这样的事情。

Updated as per comments 根据评论更新

// Source objects.
var objects = [
  { x: 3, y: 4, z: 36 },
  { x: 9, y: 5, z: 9 },
  { x: 1, y: 3, z: 100 },
  { x: 7, y: 0, z: 18 },
];

// Result object.
var result = {
    x: objects[0].x,
    y: objects[0].y,
    z: objects[0].z
};

// Set the maximum value for each property. 
for(var i = 1; i < objects.length; i++){
  result.x = Math.max(result.x, objects[i].x);
  result.y = Math.max(result.y, objects[i].y); 
  result.z = Math.max(result.z, objects[i].z); 
}

Ok, found the glitch. 好的,发现了小故障。 I initiated the result object by simply copying one of the source objects, generating a completely new object would fix it. 我通过简单地复制源对象之一来初始化结果对象,生成一个全新的对象将对其进行修复。 Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM