for (initialExpression; condition; incrementExpression)
statement
例子
var substr = [1, 2, 3, 4];
//loop from 0 index to max index
for(var i = 0; i < substr.length; i++) {
console.log("loop", substr[i])
}
//reverse loop
for(var i = substr.length-1; i >= 0; i--) {
console.log("reverse", substr[i])
}
//step loop
for(var i = 0; i < substr.length; i+=2) {
console.log("step", substr[i])
}
因为在
//dont really wnt to use this on arrays, use it on objects
for(var i in substr) {
console.log(substr[i]) //note i returns index
}
对的
for(var i of subs) {
//can use break;
console.log(i); //note i returns value
}
forEach
substr.forEach(function(v, i, a){
//cannot use break;
console.log(v, i, a);
})