JavaScript数组减少

时间:2012-07-05 09:21:16

标签: javascript arrays

function init(){
var panel = document.getElementById("panel");
var i;

var week = ["monday","tuesday","wednesday","thursday","friday"];
var weekend = ["saturday","sunday"];

panel.innerHTML+="weekdays: "+ week;
panel.innerHTML+="<hr>weekend days: "+ weekend;

for(i=0; i<weekend.length; i++)
{
    week[week.length]=weekend[i];
}

panel.innerHTML+="<hr>increased with weekend days: "+week;

week-=2;

panel.innerHTML+="<hr>reduced back to weekdays: "+week;
}
window.onload=init;

这是从另一个html文件加载的主要js代码。一切都很好,直到最后。最后的输出应该减少到工作日:星期一,星期二,星期三,星期四,星期五&#34;但是我得到的是这个&#34;减少到工作日:NaN&#34;,这个错误意味着什么,我该如何解决?

4 个答案:

答案 0 :(得分:6)

您应该将数组长度减少2,而不是数组本身:

week.length -= 2;

示例:

var week = [1,2,3,4,5,6,7];
week.length -= 2;

console.log(week);
//[1, 2, 3, 4, 5]

答案 1 :(得分:2)

您无法从数组中减去数字并期望获得有意义的结果。那就是混合类型,当然行为会很奇怪。

要让周末休息一天,请使用数组对象的pop()方法。

答案 2 :(得分:1)

也许你必须改变:

week-=2;

为:

week = week.splice(-2);

编辑(感谢@Esailija):

splice返回已删除的元素,因此您只需调用splice方法,而无需将结果返回给数组:

week.splice(-2);

答案 3 :(得分:0)

function init(){
var panel = document.getElementById("panel");
var i;

var week = ["monday","tuesday","wednesday","thursday","friday"];
var weekend = ["saturday","sunday"];

panel.innerHTML+="weekdays: "+ week;
panel.innerHTML+="<hr>weekend days: "+ weekend;

for(i=0; i<weekend.length; i++)
{
    week[week.length]=weekend[i];
}

panel.innerHTML+="<hr>increased with weekend days: "+week;

week.length -= 2;

panel.innerHTML+="<hr>reduced back to weekdays: "+week;
}
window.onload=init;

但这不是使用.length作为setter的好方法!