2016-03-03 26 views
0

當我在javascript中創建兩個數組並嘗試使用'concat'關鍵字連接它們時,結果數組始終是空的(以及應插入的數組中的內容未被插入)。我無法想象這實際上是如何js應該工作,因爲那麼...如果concat關鍵字什麼都不做,concat關鍵字的重點是什麼。哈哈。爲什麼數組串聯不能在Javascript中工作?

那麼我必須做錯了什麼,但我完全按照文檔。

以下是一個演示我的問題一個小提琴:https://jsfiddle.net/webwhizjim/7z4v33of/

// Example with objects- doesn't work... 
var greetings = [{"affirmative":"yeah"}]; 
var exclamations = [{"omg":"Oh my golly-gee-wilickers!"},{"wowz":"wowzers!"}]; 

var obArray = []; 

obArray.concat(greetings); 
console.log("The jumble array is: " + obArray); 

// Example with strings- still doesn't work... 

var greetings2 = ["affirmative","yeah"]; 
var exclamations2 = ["omg"]; 

var obArray2 = ["huh?"]; 

[].concat.call(obArray2, greetings2); 
console.log("The jumble array is: " + obArray2); 

只是要通過「它不工作」我的意思是控制檯輸出是這樣明確的:

enter image description here

PS 。在我真正的項目中,我使用的是角1.4,所以如果有一種方法可以將數組連接起來,我可以使用它。

+8

'concat'返回一個新的數組,它不會變異。 – elclanrs

+3

^'obArray2 = obArray2.concat(greetings2)' – adeneo

+1

另外,Function.prototype.call的第一個參數定義了調用的上下文(this的值),而不是第一個要連接的數組 – Sebas

回答

2

.concat()創建一個新數組並返回它。它不會將元素添加到現有陣列上。

MDN

的concat創建新的數組上 包括在對象中的元素的調用它,接着爲了通過,對於每個參數,該參數的 元件(如果參數是一個數組)或 參數本身(如果參數不是數組)。

concat不會更改此參數或任何作爲參數 提供的陣列,而是返回一個淺度副本,其中包含從原始數組組合的相同 元素的副本。

可以與.splice().push()添加元素到現有陣列:原 數組的元素如下被複制到新的數組。

var greetings2 = ["affirmative","yeah"]; 
 
var obArray2 = ["huh?"]; 
 
obArray2.push.apply(obArray2, greetings2); 
 

 
// display result in snippet 
 
document.write(JSON.stringify(obArray2));


或者,只是使用從.concat()新返回數組:

var greetings2 = ["affirmative","yeah"]; 
 
    var obArray2 = ["huh?"]; 
 
    var newArray = obArray2.concat(greetings2); 
 

 
    // display result in snippet 
 
    document.write(JSON.stringify(newArray));

0

嘗試以下操作:

var greetings = [{"affirmative":"yeah"}]; 
var exclamations = [{"omg":"Oh my golly-gee-wilickers!"}, {"wowz":"wowzers!"}]; 

var obArray = Array.prototype.concat.apply([], greetings, exclamations); 
console.log("The jumble array is: " + obArray); 
//Console Output: The jumble array is: [object Object] 

var greetings2 = ["affirmative","yeah"]; 
var exclamations2 = ["omg"]; 

var obArray2 = [].concat(greetings2, exclamations2); 
console.log("The jumble array is: " + obArray2); 
//Console Output: The jumble array is: affirmative,yeah,omg 
0

像其他人一樣,.concat返回一個新的數組,並且不會改變您正在使用的數組的原始狀態。如果你想通過.concat連接兩個數組的值,你必須將它存儲在一個變量中,或者簡單地將它連接到你需要它的地方。

例如:

var greetings = [{"affirmative":"yeah"}]; 
var exclamations = [{"omg":"Oh my golly-gee-wilickers!"},{"wowz":"wowzers!"}]; 

var obArray = greetings.concat(exclamations); 

console.log(obArray); // returns [obj, obj, obj] 

這將給你相同的結果:

console.log(greetings.concat(exclamations)); 

最後一件事。像.concat這樣的方法是可鏈接的。

相關問題