2016-10-03 31 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屬性。