Reputation: 18123
I have a basic for loop where I determine the value, 'left'
or 'right'
, of a variable called animationDirection
.
How can I initialize this variable before the loop so that it can be defined with in it?
I've tried initializing it to undefined
, by using var animationDirection = undefined;
but this is frowned upon by javascript linter.
I've settled on the code below that defines animationDirection in the loop logic, but this seems like a bad idea because I'm initializing the variable with var
twice.
Any ideas on how to better define the variable?
for (var i = 0; i < $selected.length; i++) {
if (i < ($selected.length / 2)) {
var animationDirection = 'left';
} else {
animationDirection = 'right';
}
$($selected[i])
.css(animationDirection, animationOffset)
.velocity(animation, animationConfig);
}
Upvotes: 0
Views: 69
Reputation: 101730
Like this:
var animationDirection,
i;
for (i = 0; i < $selected.length; i += 1) {
if (i < ($selected.length / 2)) {
animationDirection = 'left';
} else {
animationDirection = 'right';
}
$($selected[i])
.css(animationDirection, animationOffset)
.velocity(animation, animationConfig);
}
Douglas Crockford's JSLint requires that variables be declared at the top of a function (not sure what lint you're using).
Here's a more concise approach that avoids the for
-loop semantics (assuming here that $selected
is a jQuery object) and makes the question of where to declare your variable much simpler:
$selected.each(function(i, e) {
var animationDirection = (i < ($selected.length / 2)) ? "left" : "right";
$(e).css(animationDirection, animationOffset)
.velocity(animation, animationConfig);
});
Upvotes: 1
Reputation: 3254
How about?
for (var i = 0; i < $selected.length; i++) {
$($selected[i])
.css(i < ($selected.length / 2) ? 'left': 'right' , animationOffset)
.velocity(animation, animationConfig);
}
Upvotes: 0