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;
this is the main js code it is loaded from another html file. everything is working fine until the end. the last output should be "reduced back to weekdays: monday,tuesday,wednesday,thursday,friday" but what im getting is this "reduced back to weekdays: NaN", what does this error mean and how can i fix it?
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;
this is the main js code it is loaded from another html file. everything is working fine until the end. the last output should be "reduced back to weekdays: monday,tuesday,wednesday,thursday,friday" but what im getting is this "reduced back to weekdays: NaN", what does this error mean and how can i fix it?
Share Improve this question edited Jul 6, 2012 at 7:52 bluish 27.3k28 gold badges125 silver badges184 bronze badges asked Jul 5, 2012 at 9:21 max dmax d 211 gold badge1 silver badge4 bronze badges4 Answers
Reset to default 11You should reduce the array length by 2, not the array itself:
week.length -= 2;
Example:
var week = [1,2,3,4,5,6,7];
week.length -= 2;
console.log(week);
//[1, 2, 3, 4, 5]
maybe you have to change:
week-=2;
to:
week.splice(-2);
Edit (thanks @Esailija):
splice return the removed elements, so you have just to call the splice method, without assign the result back to the array:
week.splice(-2);
You can't subtract a number from an array and expect meaningful results. That is mixing types and of course the behavior will be weird.
To get the weekend days out, use the pop()
method of the array object.
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;
but it's not a good way to use .length
for setter!