将数组拼接成数组 Javascript

Concat arrays into array Javascript

我有一个函数,它有一个包含一年中月份的数组。在我的函数中,我删除了月份名称的一些单词。 我的功能是

var array = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];

for (var i = 0; i < array.length; i++) {
  var result = [array[i].slice(0, 3)];
  console.log(result);
}

结果是["Ene"] ... ["Dic"] 但我想要这样的:["Ene", ... , "Dic"] 我如何将结果连接到一个唯一的数组中?

问题:

在OP代码中,语句

var result = [array[i].slice(0, 3)];

for循环的每次迭代中创建一个变量result,并分配一个包含一个元素的数组,因此在循环完成执行后,result变量将只包含最后一个元素 ["Dic"].

解法:

要将元素添加到数组,请使用 Array#push

var array = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];

// Declare new empty array
var result = [];

// Loop over main array
for (var i = 0; i < array.length; i++) {
  // Add the new item to the end of the result array
  result.push(array[i].slice(0, 3));
}
console.log(result);


使用Array#map

var array = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];

var months = array.map(function(e) {
  return e.substr(0, 3);
});
console.log(months);

result 是一个空数组,push() 到它。

var result = [];
var array = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
for(var i=0; i<array.length; i++){
   result.push(array[i].slice(0,3));
}
console.log(result);

The slice() method returns the selected elements in an array, as a new array object. - http://www.w3schools.com/jsref/jsref_slice_array.asp

The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. - http://www.w3schools.com/jsref/jsref_substr.asp