循环的结果不能正常工作

时间:2016-07-16 17:21:05

标签: javascript arrays loops iteration

  1. 我想遍历一个数组。
  2. 任何长度大于3的索引我想缩写。
  3. 我想将新缩写的月份放入新的数组中。
  4. 我想通过将结果写入控制台来测试它的工作原理。
  5. 我可以让代码运行,但结果不会像我希望的那样出现。根据我的理解,循环运行,运行if语句,运行true,运行代码块。在此之后,循环应该迭代并继续,只要i< months.length,但它没有。

    
    
    var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var monthsAbbrev = [];
    
    for (var i = 0; i < months.length; i++) {
    if (months[i].length > 3) {
    monthsAbbrev = months[i].slice(0, 3);
    }
    }
    
    console.log(monthsAbbrev);
    &#13;
    &#13;
    &#13;

4 个答案:

答案 0 :(得分:4)

您只需使用Array.prototype.map()

即可
9

顺便说一下,你的代码中的目标数组不是pushing,这就是问题所在。

答案 1 :(得分:1)

您需要将月份添加到monthsAbbrev数组中。一种方法是使用var months = ["January", "Febuary"]; //sample data for better understanding var monthsAbbrev = months.map(v => v.substr(0,3)); console.log(monthsAbbrev); //["Jan", "Feb"] 函数:

.push()

答案 2 :(得分:1)

你只需要推动形成的阵列。休息你已经拥有它了。

var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];

for (var i = 0; i < months.length; i++) {
  if (months[i].length > 3) {
    monthsAbbrev.push(months[i].slice(0, 3));
  }
}

console.log(monthsAbbrev);

答案 3 :(得分:1)

除了推动之外,您可以省略检查长度&gt; 3,因为切片已经在做,并且可以防止错过某个月,例如'May'

&#13;
&#13;
var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];

for (var i = 0; i < months.length; i++) {
    monthsAbbrev.push(months[i].slice(0, 3));
}

console.log(monthsAbbrev);
&#13;
&#13;
&#13;