1
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 代码。一切正常,直到最后。最后一个输出应该是“减少到工作日:星期一,星期二,星期三,星期四,星期五”,但我得到的是“减少到工作日:NaN”,这个错误是什么意思,我该如何解决?

4

4 回答 4

10

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

week.length -= 2;

例子:

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

console.log(week);
//[1, 2, 3, 4, 5]
于 2012-07-05T09:24:31.300 回答
5

也许你必须改变:

week-=2;

至:

week.splice(-2);

编辑(感谢@Esailija):

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

week.splice(-2);
于 2012-07-05T09:29:42.563 回答
2

您不能从数组中减去一个数字并期望得到有意义的结果。那是混合类型,当然行为会很奇怪。

要获得周末,请使用pop()数组对象的方法。

于 2012-07-05T09:24:33.547 回答
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 的好方法!

于 2012-07-05T09:51:57.910 回答