Is this shortcut
var cars = [ "ford", "toyota"];
for (var i = 0, car; i < cars.length, car = cars[i]; i++) {
console.log(car);
}
for
var cars = [ "ford", "toyota"];
var car;
for (var i = 0; i < cars.length; i++) {
car = cars[i];
console.log(car);
}
good or bad practice?
I have been using longer code notation for some time now, because the processed array name isn't always that short (cars), but now I tried to minimize it and found the solution.
It's not a good practice.
If you not wanna to access by using index
try to use forEach
instead
like this
var cars = [ "ford", "toyota"];
cars.forEach(function(car,index){
console.log(car);
})
If wanna to use break then use some or every
Try like this
var cars = [ "ford", "toyota"];
cars.some(function(car,index){
console.log(car);
return true; // break on return true
})
var cars = [ "ford", "toyota"];
cars.every(function(car,index){
console.log(car);
return false; // break on return false
})
I prefer this:
cars.forEach(function(car, i) {
...
});
since you've then got completely enclosed scope for the parameters car
and i
.
You have already got solutions using .forEach()
, here is solution with while loop:
var cars = ["ford", "toyota"]; var car, i = 0; while (car = cars[i++]) console.log(car);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.