Domanda

I have created a for loop in JavaScript which looks like the following:

for (var i = 0; i < element[child].length; i++) {
    ...some code...
}

However when I run JSLint on it, it complains that the 'var i' should be moved to the beginning of the function (which seems odd to me to do) and it also complains that the ++ on the 'i++' is unexpected. It is this part that I really find weird - why is the ++ unexpected and what should it be replaced with?

È stato utile?

Soluzione 2

It is saying to move the var i out. It should be something like:

function foo() {
    "use strict";
    var i, element, child;

    //...set element/child...

    for (i = 0; i < element[child].length; i += 1) {
        //...some code...
    }
}

There is a nice post covering the ++ topic here: Why avoid increment ("++") and decrement ("--") operators in JavaScript?

Altri suggerimenti

The variables should be declared at the top of the function because that's what JavaScript ends up doing anyway (it's known as "variable hoisting"), so JSLint thinks it's clear to always have them there.

Regarding i++, it wants you to use i += 1. From JSLint docs:

The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. Also, preincrement/postincrement confusion can produce off-by-one errors that are extremely difficult to diagnose. There is a plusplus option that allows the use of these operators.

In short, JSLint believes it's evil, which is controversial. See also: http://jslinterrors.com/unexpected-plus-plus/

Honestly, I think your code is fine and the issue is more with JSLint being too picky. When I run your code through JSHint I get no problems: http://www.jshint.com/

Remember that JSLint will often be very picky even if something still works correctly. You just have to know when to take its advice and when to ignore it :)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top