代码之家  ›  专栏  ›  技术社区  ›  Teight

javascript是否可以生成变量内容的新版本

  •  0
  • Teight  · 技术社区  · 6 年前

    所以首先我为我不知道该怎么问的那个坏问题道歉。im试图做的是给一个类分配一个变量,然后使用该变量将其特定类的属性的副本添加到一个数组中。所以

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

    这不起作用,但我想基本上做到这一点,我想知道我会怎么做。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Eddie D    6 年前

    您可以编写一个生成克隆的方法,这取决于您需要克隆的具体程度和动态性。但除此之外,我对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);

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

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

        2
  •  0
  •   StackSlave    6 年前

    我创建了这个递归 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);

    然而,在您的情况下,您可能只想这样做:

    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);