- for…in…
这种方法虽可以遍历数组,但不推荐,他是遍历对象的独有方式
var teachers = [
{ name: "张三", score: 100 },
{ name: "李四", score: 78 },
{ name: "王五", score: 88 },
{ name: "赵柳", score: 90 },
{ name: "胖虎", score: 88 },
]
for(var i in teachers){
console.log(teachers[i]);
}
- every方法(官方提供的)
var teachers = [
{ name: "张三", score: 100 },
{ name: "李四", score: 78 },
{ name: "王五", score: 88 },
{ name: "赵柳", score: 90 },
{ name: "胖虎", score: 88 },
]
let result = teachers.every(function (item, index, arr) {
console.log("item:", item)
console.log("index:", index)
console.log("arr:", arr)
})
return true
- some方法 (官方提供的方法)
var teachers = [
{ name: "lily", age: 31, married: true },
{ name: "tom", age: 26, married: false },
{ name: "john", age: 34, married: true },
{ name: "lucy", age: 25, married: false },
]
var result = teachers.some(function (item, index, arr) {
console.log("item:", item)
console.log("index:", index)
console.log("arr:", arr)
return item.age > 35
})
console.log(result ? "存在年龄>35" : "不存在年龄>35")
- forEach(官方提供)此方法较为简单,为多数程序员常用方法
var emps = [
{ name: "东东", age: 23 },
{ name: "楠楠", age: 19 },
{ name: "倩倩", age: 33 },
]
emps.forEach(item=>console.log(item))
- map(官方提供)
var names = ["lucy", "lily", "john", "tom"]
var new_names = names.map(function (item, index, arr) {
return index + item.toUpperCase()
})
console.log("new_names:", new_names)
console.log("names:", names)
- filter (官方提供)
var emps = [
{ name: "亮亮", gender: "男", age: 20 },
{ name: "亚楠", gender: "女", age: 25 },
{ name: "梦瑶", gender: "女", age: 29 },
{ name: "铭铭", gender: "男", age: 32 },
]
var girls = emps.filter(function (item) {
return item.gender == "女"
})
console.log(girls)
- reduce (官方提供)
var emps = [
{ name: "lucy", salary: 8000 },
{ name: "mike", salary: 5500 },
{ name: "tom", salary: 11000 },
{ name: "jerry", salary: 7900 },
]
var sum = 0
emps.forEach(function (item) {
sum += item.salary
})
console.log(sum)
- for…of… 一种快速遍历数组到方法
var nums = [11, 22, 33, 44, 55, 66]
for (let value of nums) {
console.log("value:", value)
}