Reputation: 21
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?
Upvotes: 1
Views: 18890
Reputation: 151
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);
Upvotes: 5
Reputation: 4549
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!
Upvotes: 0
Reputation: 46193
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.
Upvotes: 2
Reputation: 140230
You 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]
Upvotes: 11