Javascript: Basic for loop is not working -
is there reason why following not work:
for (i=0;i < somearray.length;i++) { if (somearray[i].indexof("something") !== -1) { //do here } }
the basic "for" loop possible. doesn't work. on first line (declaration of loop, not inside loop), "uncaught reference error; not defined."
i have page open in 1 chrome tab, , earlier version of page open in tab. in other tab, loop works fine; in first tab, code throws error.
edit - july 2 2015
the response strict mode helpful. after reading bit , going through code i've got handle on what's going on.
the confusing bit both versions of code this, minor differences (requirejs module):
define( 'viewmodels/someviewmodel', ['dependency1', 'dependency2', 'dependency3'], function(dep1, dep2, dep3) { "use strict"; function someviewmodel(arg1, arg2) { var self = this; self.initialize(); self.removerefinement = function(refinementstring) { var refinementarray = refinementstring.split("&"); (i=0;i < navigationarray.length;i++) { //<-- error } } } } );
one version throws reference error. 1 doesn't.
this large web application many other pages , javascript files. thing think of in 1 version of code, maybe had been inadvertently globally defined somewhere else in app, strict mode wasn't enabled. after running breakpoint , checking "window" see that's what's happening.
thanks =d
if in strict mode, you'll error uncaught reference error; not defined.
if you're not in strict mode, won't error.
this throw error
'use strict' var somearray = ['aaa', 'bbb', 'ccc']; (i=0;i < somearray.length;i++) { console.log(i) if (somearray[i].indexof("something") !== -1) { //do here } }
this won't
var somearray = ['aaa', 'bbb', 'ccc']; (i=0;i < somearray.length;i++) { console.log(i) if (somearray[i].indexof("something") !== -1) { //do here } }
Comments
Post a Comment