javaScript 的数组的一些核心方法

concat

连接2个或更多数组,并返回结果

let a = [1,2,3];
let b = [6,7,8,9];

let c = b.concat(a)
// console.log(c);   [6,7,8,9,1,2,3]

every

对数组中的每一项运行给定函数,如果该函数对每一项都返回true,则返回true

let a = [1,2,3];

let b =  a.every(item=>{
    return item > 1
})
console.log(b);  //false
let a = [1,2,3];

let b =  a.every(item=>{
    return item >= 1
})
console.log(b);  //true

filter

对数组中的每一项运行给定函数,返回该函数会返回true的项,组成的数组

let a = [1,2,3];

let b =  a.filter(item=>{
    return item > 1
})
console.log(b);  //[2,3]
let a = [1,2,3];

let b =  a.filter(item=>{
    return item >= 1
})
console.log(b);  //[1,2,3]

forEach

对数组中的每一项运行给定函数,这个方法没有返回值

let a = [1,2,3]

a.forEach((item,index)=>{
    console.log(index+ '----' +item);  //0----1 1----2 3----3
})

join

将所有的数组元素连接成一个字符串

let a = [1,2,3]

let b = a.join('=')
console.log(b);  //1=2=3
console.log(typeof b);  //string

indexOf

返回第一个与 给定参数 相等的数组元素的 索引,没有找到则返回 -1

let a = [1,2,3]
let b = a.indexOf(2)
console.log(b); //1
let a = [1,2,3]
let b = a.indexOf(5)
console.log(b); //-1

lastIndexOf

返回在数组中搜索到的与 给定参数 相等的元素的 索引 的最大的值

let a = [1,2,3,2,3,5,2]
let b = a.lastIndexOf(2)
console.log(b); //6

map

对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组

let a = [1,2,3]

let b = a.map(item=>{
    return item+1
})
console.log(b); //[2,3,4]

reverse

颠倒数组中元素的顺序,原先第一个元素现在变成最后一个元素,同样原先最后一个元素变成了现在的第一个

let a = [1,2,3]

let b = a.reverse()
console.log(b); //[ 3, 2, 1 ]

slice

传入索引值,将数组里对应索引范围的元素作为新数组返回,不会改变原始数组。

let a = [1,2,3]

let b = a.slice(0,2)//包含索引0,不包含索引2
console.log(b);  //[ 1, 2 ] 

some

对数组中的每一项运行给定函数,如果该函数任一项返回true,则返回true

let a = [1,2,3]

let b = a.some(item=>{
    return item>1
})
console.log(b); //false

sort

按照字母顺序对数组排序,支持传入指定排序方法的函数作为参数

字母:

let a = ['b','c','a']

let b = a.sort()
console.log(b); //[ 'a', 'b', 'c' ]

数字:

let a = [3,5,4,2,1]

let b = a.sort((a,b)=>{
    return a-b
})
console.log(b); //[ 1, 2, 3, 4, 5 ] 升序

let c = a.sort((a,b)=>{
    return b-a
})
console.log(c); //[ 5, 4, 3, 2, 1 ]降序

toString

将数组作为字符串返回

let a = [1,2,3]

let b = a.toString()
console.log(b); //1,2,3
console.log(typeof b); //string
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值