Home > Mobile >  JavaScript arrays and understanding arr[arr.length]
JavaScript arrays and understanding arr[arr.length]

Time:10-20

What is meant by arr[arr.length]. I mean what it really means or what it really does, I cannot understand the logic of how it works. Can anybody explain?

CodePudding user response:

arr.length is the length of the array.

arr[arr.length] is accessing by index the array length (out of bounds as length starts at 1, not index 0).

example:

const test = [1,2,3]
test[test.length]
undefined
test[test.length-1]
3

CodePudding user response:

It just requests specific index of the array, Use case: Not very elegant way of adding new element to the array, like:

arr[arr.length] = newVal
arr.push(newVal)
arr = [...arr, newVal]

CodePudding user response:

arr.length means the length of the array that spans from index 0 to arr.length - 1.

For instance if you got arr = ["a", "b", "c"], arr.length is 3.

arr[0] is "a", arr[1] is "b" and arr[2] is "c".

arr[3] does not exist, yet. but if you do arr[arr.length] = "d", you obtain ["a", "b", "c", "d"].

This is an odd construction and usually, one should simply write arr.push("d").

const arr = ["a", "b", "c"];
console.log(arr.length, arr[0], arr[1], arr[2], arr[3]);
arr[arr.length] = "d";
console.log(arr);
arr.push("e");
console.log(arr);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This statement gets the index of the last index of the array plus one. It is used to append items to an array. Equivalent to array.push().

var fruits = ["apple", "orange", "banana", "pear"];
// appends grapes to the array
fruits[fruits.length] = "grapes";
console.log(fruits);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

For further reading, check out W3School's page on array methods.

CodePudding user response:

Actually i am studyieng javascript at the moment and i wanted to understand this code from w3school.

  let len = arr.length;
  let max = -Infinity;
  while (len--) {
    if (arr[len] > max) {
      max = arr[len];
    }
  }
  return max;
}```
  • Related