js 数组

2020-09-29  本文已影响0人  Vergil_wj

1、字符串数组转整形数组:

['1','2','3'].map(Number)  //[1,2,3]

2、slice(start,end)数组截取,不改变原始数组,返回新数组。

[1,2,3,4,5].slice(0,3)  //[1,2,3]
[1,2,3,4,5].slice(-2,-1)  //[4]

其中start,end关系为左闭右开区间[0,3),[-2,-1)

3、splice(index,howmany,item)数组增删改,改变原始数组,返回被删除的元素。

var arr = [1,2,3,4,5]
var a = arr.splice(1,0,"add")
console.log(a)  //[]
console.log(arr)  //[1, "add", 2, 3, 4, 5]

//删除一个
var arr = [1,2,3,4,5]
var a = arr.splice(1,1)
console.log(a)  //[2]
console.log(arr)  //[1, 3, 4, 5]

//删除两个
var arr = [1,2,3,4,5]
var a = arr.splice(1,2)
console.log(a)  //[2,3]
console.log(arr)  //[1, 4, 5]

//从下标开始,后面全部删除
var arr = [1,2,3,4,5]
var a = arr.splice(1)
console.log(a) //[2, 3, 4, 5]
console.log(arr)  //[1]

var arr = [1,2,3,4,5]
var a = arr.splice(1,1,99)
console.log(a)  //[2]
console.log(arr)  //[1, 99, 3, 4, 5]

参考:
https://www.runoob.com/jsref/jsref-obj-array.html

上一篇下一篇

猜你喜欢

热点阅读