简体   繁体   中英

Concat arrays into array Javascript

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM