【问题标题】:Errors result when attempting to copy an array尝试复制数组时出现错误
【发布时间】:2016-10-03 15:31:35
【问题描述】:

我正在尝试复制一个数组,但是我不断遇到问题。我尝试了 2 种不同的方法,但都没有奏效。

第一次尝试:

function classA(id, arrayFrom, arrayTo)
{
  this.id = id;
  this.from = arrayFrom.slice(0);
  this.to = arrayTo.slice(0);
};

输出:

未捕获的类型错误:arrayFrom.slice 不是函数

第二次尝试:

function classA(id, arrayFrom, arrayTo)
{
  this.id = id;
  this.from = {arrayFrom[0], arrayFrom[1], arrayFrom[2]};
  this.to = {arrayTo[0], arrayTo[1], arrayTo[2]};
};

输出:

Uncaught SyntaxError: Unexpected token [

【问题讨论】:

  • 无用的细节。与对该函数的调用共享代码。
  • 方法很好,无论你传递给它们什么,它们都不是数组
  • arrayFrom 不是一个数组。请告诉我们它到底是什么。
  • 顺便说一句,这些函数都不会复制数组^^
  • @SteevePitis slice(0),将复制一个数组。它不会做的是深拷贝,但对于整数等原始类型来说就可以了。

标签: javascript arrays


【解决方案1】:

您可以使用真实数组初始化您的实例。然后它可以正常工作。

function classA(id, arrayFrom, arrayTo) {
    this.id = id;
    this.from = arrayFrom.slice(0);
    this.to = arrayTo.slice(0);
}

var aFrom = [1, 2, 3],
    aTo = [42, 43, 44],
    a = new classA(0, aFrom, aTo);

aFrom[0] = 100;
console.log(a); // the instance does not change to 100

【讨论】:

    【解决方案2】:

    如果您使用“类似数组”的可迭代参数(例如节点列表)调用 ClassA,那么您可能会像 this.from = Array.from(arrayFrom) 那样做。

    function ClassA(id, arrayFrom, arrayTo) {
        this.id = id;
        this.from = Array.from(arrayFrom);
        this.to = Array.from(arrayTo);
    }
    
    var obj = new ClassA(1,{0:"a",1:"b",length:2},{length:0});
    console.log(obj);

    Array.from() 可以工作,即使提供的对象没有迭代器而只有一个 length 属性。

    【讨论】:

      【解决方案3】:
      function classA(id, arrayFrom, arrayTo){
        this.id = id;
        this.from = arrayFrom.slice(0, arrayFrom.length);
        this.to = arrayTo.slice(0, arrayTo.length);
      }
      

      让我们试试这个:) 但是您的函数没有复制数组...我只是正确地编写了您的代码;)

      【讨论】:

      • "arrayFrom.slice 不是函数"
      • 看来他没有传递数组:\
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多