Concat arrays into array Javascript

ⅰ亾dé卋堺 提交于 2020-01-16 05:26:24

问题


I have a function that has an array with the months of the year. In my function i delete some words of the month name. My function is

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);
}

The result is ["Ene"] ... ["Dic"] But i want have some like this: ["Ene", ... , "Dic"] How i can concat the result in a unique array?


回答1:


Problem:

In OP code, the statement

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

is creating a variable result in each iteration of the for loop and assigning an array having one element in it, so after loop finishes execution, the result variable will only contain the last element ["Dic"].

Solution:

To add the elements to array, use 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);

Use 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);



回答2:


Have result be an empty array and push() to it.

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);



回答3:


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



来源:https://stackoverflow.com/questions/34084274/concat-arrays-into-array-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!