2016-10-03 33 views
0

我试图复制一个数组的时候,但是我不断收到问题。我尝试过两种不同的方式,但都没有成功。错误导致试图复制一个数组

第一次尝试:

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

输出:

Uncaught TypeError: arrayFrom.slice is not a function

第二次尝试:

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 [

+2

无用的细节。与该函数的调用共享代码。 –

+2

这些方法很好,无论你传给它们,它们都不是数组 – Yoda

+2

'arrayFrom'是* not *数组。请告诉我们它的实际情况。 –

回答

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

让我们试试这个:) 但你的职责并没有复制一个数组...我只是写对你的代码;)

+0

“* arrayFrom.slice不是函数*” –

+0

他似乎没有传递数组:\ –

0

你可以与真正的数组初始化您的实例。然后它没有错误地工作。

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

0

如果调用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属性。