我可以让代码运行,但结果不会像我希望的那样出现。根据我的理解,循环运行,运行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;
答案 0 :(得分:4)
答案 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'
。
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;