数组遍历for
var array = [1,2,3,4,5,6,7];
for (var i = 0; i < array.length; i) {
console.log(i,array[i]);
}
forEach() 方法
array.forEach(v=>{
console.log(v);
});
array.forEach(function(v){
console.log(v);
});
对数组的每个元素执行一次提供的函数
var array = ['a', 'b', 'c'];
array.forEach(function(element) {
console.log(element);
});
// 输出 a;b;c;
forEach() 方法对数组的每个元素执行一次提供的函数。总是返回undefined;
var arr = [1,2,3,4];
arr.forEach(alert);
// 等价于:
var arr = [1, 2, 3, 4];
for (var i = 0; i <arr. length; k++) {
alert(array[k]);
}
语法:
[ ].forEach(function(value,index,array){
//code something
});
forEach方法中的function回调有三个参数:
第一个参数是遍历的数组内容,
第二个参数是对应的数组索引,
第三个参数是数组本身
var arr = [1,2,3,4];
var sum =0;
arr.forEach(function(value,index,array){
array[index] == value; // true
sum+=value;
});
console.log(sum); // 10
for in
for(let index in array) {
console.log(index,array[index]);
};
也能对对象遍历
var A = {a:1,b:2,c:3,d:"hello world"};
for(let k in A) {
console.log(k,A[k]);
// a 1
// b 2
// c 3
// d hellow world
}
当使用for in 遍历时,会将所有属性包括下标都会转为字符型
for(var num in arr){
console.log(num);
数组的下标,如果给的是字符,会转换成数值
console.log(arr[num])
}
1、for in 不会遍历空元素,for会遍历空元素
2、for in可以遍历到数组的属性,for 只能遍历数组的所有下标,不能遍历属性
属性包含字符和下标(数字)
for of
在ES6中,增加了一个for of循环
for(let v of array) {
console.log(v);
};
let s = "helloabc";
for(let c of s) {
console.log(c);
}
总:
:for in总是得到对象的key或数组,字符串的下标,而for of和forEach一样,是直接得到值
结果for of不能对象用