Tell me the difference by example, initially - undefined . If I change as in the comment, then everything is fine!

 var days = ['Mon','Tues','Wed','Thurs','Fri','Sat','Sun']; for(var i = 0; days.length > i ; days.length--) { document.write(days[days.length] + '<br>'); //**Если так - document.write(days[days.length-1] + '<br>') то все выводится нормально.** } document.write(days.length); // общее число единиц массива уменьшается 
  • the days [days.length] element usually does not exist in arrays :) - KoVadim
  • days [days.length] is the index of access to the elements of the array. - adidassler
  • one
    Yeah, you can use instead of .push() > Prompt the difference on the example of the elements in array 7, but since indexing comes from scratch, the last element of the 6th, what's the problem I do not understand? for (var i = days.length; i--;) {// start with the last element and decrease the document.write counter (days [i] + '<br>'); } - Specter
  • Thanks for the examples, but I want to figure out why logically when decreasing days.length-- in document.write (days [days.length]) all 7 values ​​are undefined !? although days.length decreases from 7 to 0. Why, when decreasing, starting from index number 6 does it not display the value of the array? - adidassler
  • one
    because for (var i = 0; days.length> i; days.length--) {document.write (days [days.length] + '<br>'); } is equivalent to for (var i = 0; days.length> i;) {document.write (days [days.length] + '<br>'); days.length--; } and if you are running days.length-- , it automatically reduces the number of array elements per unit proof: var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat' , 'Sun']; days.length--; console.log (days); // ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"] - Specter

2 answers 2

What a horror.

 var days = ['Mon','Tues','Wed','Thurs','Fri','Sat','Sun']; for(var i = 0; i < days.length; i++) { document.write(days[i] + '<br>'); } document.write(days.length); 
  • I meant not first output, but from the end. - adidassler
  • var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; for (var i = days.length - 1; i> = 0; i--) {document.write (days [i] + '<br>'); } document.write (days.length); - Mobyman

In JavaScript, there is a special method for inverting an array — reverse () .

If it's so interesting to play with sorting, then try the method - sort () .