Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!1.eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: Reverse elements in array, they can be integers or strings. Date: Sun, 17 May 2015 00:28:22 +0100 Organization: A noiseless patient Spider Lines: 54 Message-ID: <87lhgom7ah.fsf@bsb.me.uk> References: <2ddccd07-49e4-42c3-9ecc-27f047078f84@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="017616aa25f81ec581c44d76d61ba2f3"; logging-data="19583"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/t/UbKtNmQQrgwqA8Wqd/XzGI+oIZg2VA=" Cancel-Lock: sha1:fHt6Dg+ND8/6VA6p2sn1/ymzbAs= sha1:Tpz4RBacdH3dgahJ2HwLT50Tqxg= X-BSB-Auth: 1.78b798b7911648c6a02d.20150517002822BST.87lhgom7ah.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:27703 Denis McMahon writes: > On Sat, 16 May 2015 15:00:42 +0200, Evertjan. wrote: > >> jonas.thornvall@gmail.com wrote on 16 mei 2015 in comp.lang.javascript: > >>> var arrLength; >>> arrLength=thisArr.length; >>> for (i=arrLength;i>=0;i--){ >>> thisElement=thisArr[i]; > >> this will give an ERROR, >> as the highest indexed element has an index of i-1 > > Will it? The code is wrong, but whether it "gives and ERROR" depends on what was meant by that. > Given i starting at thisArr.length and executing an i-- before accessing > the array, I don't think it will give that error, the error will be on > the pass after i == 0, as it will then decrement i and execute the loop > with i having a value of -1, which is an illegal array index. You've got the place where the decrement happens mixed up -- it is done after each execution of the loop body, so the loop above initially accesses an undefined element, and then accesses all of the defined elements in sequence. An index of -1 is not used (though i == -1 at the end of the loop's execution). > All of the following are valid in c-type languages where 0 is "falsey", > numbers other than 0 are "truthy" and arrays are 0 indexed: > > for (var i = arr.length; i > 0; i--) { > // do something with arr[i] > } > > for (var i = arr.length; i; i--) { > // do something with arr[i] > } No, these are both wrong. They access an undefined element first, and neither accesses element 0. > var i = arr.length; > while (i--) { > // do something with arr[i] > } This one is correct. -- Ben.