2016-03-03 153 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这样的方法是可链接的。

相关问题