JavaScript可以创建变量内容的新版本

时间:2018-05-30 23:28:38

标签: javascript

首先,对于我不知道如何提问的不好问题,我很抱歉。我试图做的是将一个变量赋给一个类然后使用该变量将其特定类的属性的重复项添加到一个数组。所以

var apple = new Item("Apple", 5, 10); var items = []; items.push(new apple)

这不起作用但我想基本上这样做,我想知道我将如何这样做。

2 个答案:

答案 0 :(得分:0)

您可以编写一个生成克隆的方法,具体取决于您需要的具体和动态。但除此之外,我对Javascript本身的任何东西都不太熟悉。

class Person
{
  constructor(name, age, weight)
  {
    this.name = name;
    this.age = age;
    this.weight = weight;
  }

  Clone()
  {
    let myCopy = new Person(this.age, this.weight, this.weight);
    return myCopy;
  }
}

let me = new Person('Eddie', 29, 345);
let myTwin = me.Clone();
console.log(me, myTwin);

完整而深入的克隆会有一点开销。它很可能必须能够识别所有数据类型到原语并对每个数据类型做出反应。克隆数组可能涉及克隆实际数组及其内部的每个值。

它内部的每个值也可能是一个需要遵循相同过程的容器。

答案 1 :(得分:0)

我创建了这个递归copy函数,可以做你想做的事情:



function copy(mixed){
  var o, n;
  if(typeof mixed === 'object' && mixed !== null){
    if(mixed instanceof Array){
      o = [];
      for(var i=0,l=mixed.length; i<l; i++){
        n = mixed[i];
        if(typeof n === 'object'){
          n = copy(n);
        }
        o.push(n);
      }
    }
    else{
      o = {};
      for(var i in mixed){
        if(mixed.hasOwnProperty(i)){
          n = mixed[i];
          if(typeof n === 'object'){
            n = copy(n);
          }
          o[i] = n;
        }
      }
    }
  }
  else{
    o = mixed;
  }
  return o;
}
// array test
var testArray = [0, 'test', 2, {prop:'val', num:5}]
var newTestArray = copy(testArray);
testArray[3] = {prop:'another val', num:7, ary:[0, 1, 7]};
console.log(testArray);
console.log(newTestArray);

// object test
function Item(itemName, width, height){
  this.name = itemName; this.width = width; this.height = height;
}
var testObj = new Item('Apple', 5, 10);
var newTestObj = copy(testObj);
testObj.width = 30;
console.log(testObj);
console.log(newTestObj);
&#13;
&#13;
&#13;

但是,在您的情况下,您可能只想这样做:

&#13;
&#13;
function Item(itemName, width, height){
  this.name = itemName; this.width = width; this.height = height;
}
var items = [new Item('Apple', 5, 10), new Item('Orange', 7, 25), new Item('Peach', 12, 30)];
console.log(items);
&#13;
&#13;
&#13;