一、数组的遍历:
首先定义一个数组 arr=['snow','bran','king','nightking'];
1、for循环,需要知道数组的长度;
2、foreach,没有返回值,可以不知道数组长度;
arr.forEach(function(ele,index){
console.log(index);
console.log(ele)
})
3、map函数,遍历数组每个元素,并回调操作,需要返回值,返回值组成新数组,原数组不变;
var newarr=arr.map(function(i){
return "hello "+i
});
console.log(newarr)
4、filter函数:过滤通过条件的元素组成一个新数组,原数组不变;
var newarr=arr.filter(function(i){
return i == "bran"
});
console.log(newarr)
5、some函数,遍历数组中是否有符合条件的函数,返回布尔值;
var yy=arr.some(function(i){
return i.length>4
});
console.log(yy) //true
6、every函数,遍历数组是否每个元素都符合条件,返回布尔值;
var xx=arr.every(function(i){
return i.length>4
});
console.log(xx) //false
7、reduce函数,为数组中的每一个元素依次执行回调函数
语法:
arr.reduce(callback, initialValue)
[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
callback:执行数组中每个值的函数,包括四个参数;
previousValue:上一次调用回调返回的值,或者是提供的初始值(initialValue);
currentValue:当前被处理的值;
index:当前元素在数组中的索引;
array:调用reduce的数组;
initialValue:作为第一次调用callback的第一个参数;
例如:
var total = [0, 1, 2, 3].reduce(function(a, b) {
return a + b;
});
// total == 6
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]
要提供initialValue的话:
var total = [0, 1, 2, 3].reduce(function(a, b) {
return a + b;
},4);
console.log(total); //10
二、对象的遍历
var obj={snow:1,bran:2,king:3,nightking:4};
for(let i in obj){
console.log(i+','+obj[i])
}
in也可以用来遍历数组,不过i对应于数组的key值:
for(let i in arr){
console.log(i+','+arr[i])
}