遍历对象
方法1
var obj = {a: 1, b:2, c:3}
for (let f in obj) {
console.log(f, ':', obj[f])
}
a : 1
b : 2
c : 3
方法2
var obj = {a: 1, b:2, c:3}
Object.keys(obj).forEach(function(field) {
console.log(field, ':', obj[field])
})
a : 1
b : 2
c : 3
遍历数组
方法1
var arr = [1,2,3,4,5]
arr.forEach(function(ele, idx){
console.log(idx, ele)
})
0 1
1 2
2 3
3 4
4 5
方法2
var arr = [10,20,30,40,50]
for (var idx in arr){
console.log(idx, arr[idx])
}
0 10
1 20
2 30
3 40
4 50
方法3
var arr = [10,20,30,40,50]
for (var ele of arr){
console.log(ele)
}
10
20
30
40
50
map数组
var arr = [10,20,30,40,50]
arr.map(e =>e*10)
[100, 200, 300, 400, 500]
filter数组
var arr = [10,20,30,40,50]
arr.filter(e => e>25)
[30, 40, 50]
reduce数组
var arr = [10,20,30,40,50]
var sum = arr.reduce((a, s) => a+s)
sum
150
找到某一项的下标
var arr = [10,20,30,40,50]
arr.indexOf(30)
2 // 存在
arr.indexOf(3)
-1 // 不存在
找到满足谓词的第一项
arr.find(item => item%3 == 0)
30