+ 1
Can anyone explain those codes?
var arr = []; arr[0] = arr.length; arr[1] = arr.length + 4; arr[2] = arr.length + arr[1] %2; document.write(arr[2]) //output = 3 var arr = []; arr[1] = 4; arrr[0] = arr.length; arr[2] = arr.length; document.write(arr[0]+arr[2]%arr[1]) //output= 4 Why so??? I can't understand the arr.length... It'snot stay constant in the first code...Like its length for arr[0]=0,and it's lenghth for arr[1]=1. But in the second code it's length is 2 for arr[0],arr[2]...why it is not 0 for arr[0] and 2 for arr[2]??? I can't understand... please explain
1 Answer
+ 3
Length is updated as elements are removed from or added to the array.
var arr = [];
// Empty array, length = 0
arr[0] = arr.length;
// Element added, arr[0] = 0, length = 1.
arr[1] = arr.length + 4;
// Element added, arr[1] = 5, length = 2.
arr[2] = arr.length + arr[1] %2;
// arr[2] = 2 + 5 % 2 = 3
//=================
var arr = [];
// Empty array, length = 0
arr[1] = 4;
// 2 elements added, arr[0] = undefined, arr[1] = 4, length = 2.
arr[0] = arr.length;
// Element modified, arr[0] = 2.
arr[2] = arr.length;
// Element added, arr[2] = 2, length = 3.
document.write(arr[0] + arr[2] % arr[1])
// 2 + 2 % 4 = 4.