javascript - Deep understanding: What is the underlying logic behind the way array indexes work? -
my motivation question
for me thrill of programming when deep understanding of logic behind given language enables "just figure things out" using logic. when stumble upon appears miss kind logic bothers me.
how indexes work
this have learned working array indexes:
var fruit = ["apple", "orange", "kiwi"] fruit.length = 3 // returns length of fruit array var rotten = fruit[2] //assigns value "kiwi" variable "rotten" fruit[2] = "melon" //changes 3rd object in array fruit "kiwi" "melon" fruit[fruit.length] = "melon" //adds new object array fruit after "kiwi"
what bothers me logic
so have used .length
to obtain information fruit array has length of three. next want access third object using var rotten = fruit[]
. logic tells me should using var rotten = fruit[3]
. returns undefined because objects indexed 0, 1, 2.
likewise immediate thought use following code add object array: fruit[fruit.length + 1] = "melon"
because know .length
method returns "the number of last object" in array. of course not case because in reality 2 when considering index 0, 1, 2.
my question
is there deeper logic behind not indexing array using 1, 2, 3 in stead of 0, 1, 2 , thereby making - in opinion - more intuitive understand , use javascript or should learn heart , accept without looking deeper reasoning?
in fortran family languages, arrays indexed starting @ 1, suggest, since standard mathematical practice. in algol-60/pascal family of languages, programmer chooses starting index — can 0, 1, or else. in bcpl , c family of languages, , in modern languages (with notable exclusion of julia), array indices start @ 0.
over years, has been found out convenient have single convention — pascal-style indexing confusing when code written different programmers combined, better choose 1 starting index , stick it.
the actual choice between 0 , 1 arbitrary, number of wise people agree starting @ 0 makes number of operations little simpler , less error-prone. compare example following 2 implementations of array interleaving, 0-based:
if(i % 2 == 0) a[i / 2] = 42; else b[(i - 1) / 2] = 42;
and 1-based:
if(i % 2 == 1) a[(i + 1) / 2] = 42; else b[i / 2] = 42;
Comments
Post a Comment