将数组Concat转换为数组Javascript [英] Concat arrays into array Javascript

查看:44
本文介绍了将数组Concat转换为数组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);
}

结果为 [ Ene] ... [ Dic]
但我想要这样的内容: [ Ene,... , Dic]
如何将结果合并到唯一数组中?

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

推荐答案

问题:

在OP代码中,语句

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

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

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"].

解决方案:

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

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

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

这篇关于将数组Concat转换为数组Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆