程序员

js数组方法全解

2021-08-10  本文已影响0人  醉青风

会改变原数组的方法

reverse(),splice(),sort(),shift()  ,unshift()  ,push()  ,pop()

let list = [1,2,3,4,5,6,3]

 1.map 处理每个元素,并把返回的值组成新数组

let list2 =    list.map((el)=>{return el=el+1}) 

console.log(" list2 ", list2 ) //list2  (6) [2, 3, 4, 5, 6, 7]

2.filter 返回符合判断的元素组成数组

let list3 =    list.filter((el)=>{return el>3}) 

console.log(" list3 ", list3 )//list3  (3) [4, 5, 6]

3. some  判断元素是否符合判断,只有有一个符合就返回 true

let list4 =    list.some((el)=>{return el>3}) 

console.log(" list4 ", list4 )//list4  true

 4.every  判断元素是否全部符合判断

let list5 =    list.every((el)=>{return el>3}) 

console.log(" list5 ", list5 )//list5  false

5. 判断元素是否是数组

let list6 =    Array.isArray(list ) // every 

console.log(" list6 ", list6 )// list6 true

6. 找数组中是否存在该元素,有则返回该元素的下角标,否则返回-1

let list7 =    list.indexOf(13) 

console.log(" list7 ", list7 )// list7  2

7. 找数组中是否存在(符合条件的元素),只有有一个符合则返回该元素的下角标,否则返回-1

let list8 =    list.lastIndexOf( 2,13)

console.log(" list8 ", list8 )// list8 1

8.splice():删除、插入和替换。使用  splice(起始位置、 0(要删除的项数)和要插入的项)。会改变原数据

list.splice( 2,0,9) // 

console.log(" list  ",  list)// list  [1, 2, 9, 3, 4, 5, 6, 3]

9.slice(): 根据下角标截取数据,不会改变原数据

let list9 =  list.slice( 2,8) // 

console.log(" list9 ", list9 , list)// list  [1, 2, 9, 3, 4, 5, 6, 3]

10. Array.from(list,map,name)  // 其中第一个是数组,必传;第二个是一个函数(类似map函数),对数组元素进行操作后再返回数组,可选;第三个是对于 this关键字的指向,可选。

在这里我们只用前两个方法,

Array.from(list),复制数组:类似...扩展运算符的作用,返回数组

Array.from(list,item=>item*2)    可以接收,第二个参数,类似map方法的作用,对数组的每个元素处理后再返回新数组,如上:每个数组里面每个元素乘2

11. new Set(list)    拥有给list去重的作用  

// sort() 排序

// reverse():反转数组项的顺序

// concat() :合并数组

// shift():删除原数组第一项,并返回删除元素的值;如果数组为空则返回undefined 。

// unshift:将参数添加到原数组开头,并返回数组的长度 。

//push():  把里面的内容添加到数组末尾,并返回修改后的长度。

//pop():移除数组最后一项,返回移除的那个值,减少数组的length。

//join,就是把数组转换成字符串,然后给他规定个连接字符,默认的是逗号(  ,)

上一篇 下一篇

猜你喜欢

热点阅读