数组
for、forEach、map、filter…
forEach的第二个参数
Array.forEach(function(item){...},ArrayThis)
传入forEach
的第二个参数会让function的this指向改变为第二个参数(第一个function如果为箭头函数的话则不会生效)
var a = [1,2]
a.forEach(function(item){console.log('this为--', this)},a)
// this为--[1,2]
// this为--[1,2]
a.forEach(function(item){console.log('this为--', this)},{})
// this为--{}
// this为--{}
find
Array.find(function(item){...},ArrayThis)
和filter相似,都是找到符合条件的值,但是find只返回第一个符合条件的属性
findIndex
Array.findIndex(function(item){...})
查找是否有符合条件的值,如果找到符合条件的值,停止执行,返回该值的index
includes
Array.includes(val)
判断数组中是否包含val,返回Boolean
var a = [1,2,3,4,5,6,7,8]
a.includes(5)
// true
every
Array.every(item => {...})
检测数组中的值是否符合条件,如果其中一个为false,则停止检测,返回false
var a = [1,2,3,4]
console.log(
a.every(item => {
return item > 3
})
)
// false
some
Array.some(item => {...})
检测数组中的值是否符合条件,如果去中一个为true,则停止检测则返回true
var a = [1,2,3,4]
console.log(
a.some(item => {
return item > 3
})
)
// true
reduce / reduceRight
Array.reduce((a,b) => a + b)
将数组中的每个值以从左到右的顺序累加(reduceRight是从右向左),最终返回一个值
- function中有四个参数,分别为
([上一次的值],[当前值],[当前的index],[原数组])
- Array.reduce有第二个参数,值为第一次相加前的初始值
var a = [1,2,3,4,5]
var b = a.reduce((a, b) => {
return a + b
},100)
// 115
遍历对象
for in、for of…
Object.keys
Object.keys(obj)
返回一个数组,数组中包括对象obj中的所有(可枚举)属性名称
a = {a: 1, b: 2, c: 3, d: 4}
Object.keys(a)
// ["a", "b", "c", "d"]
getOwnPropertyNames
Object.getOwnPropertyNames(obj)
返回一个数组,数组中包括对象obj中的所有(包括不可枚举)属性名称
Object.values
Object.values(obj)
以对象的形式返回数组
a = {a: 1, b: 2, c: 3, d: 4}
Object.values(a)
// [1, 2, 3, 4]
对对象数组的单个属性去重
var a = [{
name: '小明',
age: 20,
team: '小明团队'
},{
name: '小红',
age: 15
team: '小红团队'
},{
name: '小白',
age: 18
team: '小白团队'
},{
name: '小绿',
age: 99
team: '小彩团队'
},{
name: '小彩',
age: 24
team: '小彩团队'
}]
let newA = a.filter((item,index,arr) => {
return arr.findIndex(arrItem => arrItem.team === item.team) === index
})
利用了findIndex从左到右查找的机制,在数组中team
有重复的的情况下,如果findIndex
查找得出的index
不等于filter
当前的index
的话,则代表着arrItem
在这个数组之前的属性中存在过了,filter
返回false