使用 forEach
forEach(), 没有返回值。
list = [
{ "id": 1, name: "鞠婧祎" },
{ "id": 2, name: "关晓彤" },
{ "id": 3, name: "刘亦菲" },
]
list.forEach(function (item, index) {
console.log(index, item.name);
})
使用 map
map() 有返回值,可以return 出来。
list = [
{ "id": 1, name: "鞠婧祎" },
{ "id": 2, name: "关晓彤" },
{ "id": 3, name: "刘亦菲" },
]
list.map(function (item, index) {
item.name = "姓名:" + item.name
return item
})
console.log(list);
使用 every
- every()是对数组中每一项运行给定函数,如果该函数对每一项返回true,则返回true。
- every从迭代开始,一旦有一个不符合条件,则不会继续迭代下去。
list = [
{ "id": 1, name: "鞠婧祎" },
{ "id": 2, name: "关晓彤" },
{ "id": 3, name: "刘亦菲" },
]
let flag = list.every(function (item) {
return item.id > 2
})
console.log(flag);
使用 filter
filter() 将一个数组中的每一项都return后的条件进行比较(这里的item > 3),筛选出满足条件的数据项,并组成一个新数组
list = [
{ "id": 1, name: "鞠婧祎" },
{ "id": 2, name: "关晓彤" },
{ "id": 3, name: "刘亦菲" },
]
var foo = list.filter((item, index) => {
return item.id > 2;
})
console.log(foo);
使用 some
- some()是对数组中每一项运行给定函数,如果该函数对任一项返回true,则返回true。
- some一直在找符合条件的值,一旦找到,则不会继续迭代下去。
list = [
{ "id": 1, name: "鞠婧祎" },
{ "id": 2, name: "关晓彤" },
{ "id": 3, name: "刘亦菲" },
]
let flag = list.some(function (item) {
return item.id > 2
})
console.log(flag);