经常使用到的数组方法,过段时间需要整理一遍,工作中经常使用,偶尔想不起来
目录
- push
- concat
- unshift
- splice
push
向数组尾部追加数据
定义
push(...items: T[]): number;
示例
let list = ['tom']
list.push('Jack', 'Steve')
console.log(list)
// [ 'tom', 'Jack', 'Steve' ]
concat
合并两个数组,注意:该方法会返回新数组
定义
concat(...items: (T | ConcatArray<T>)[]): T[];
示例
let list = ['tom']
let newList = list.concat('Jack', 'Steve')
console.log(list)
// [ 'tom' ]
console.log(newList);
// [ 'tom', 'Jack', 'Steve' ]
unshift
头部插入元素
定义
unshift(...items: T[]): number;
示例
let list = ['tom']
list.unshift('Jack', 'Steve')
console.log(list)
// [ 'Jack', 'Steve', 'tom' ]
splice
删除元素或插入元素,同时具有remove(Array未提供)、insert(Array未提供)、push、unshift的功能
定义
splice(start: number, deleteCount: number, ...items: T[]): T[];
示例
let list = ['tom', 'Jack']
list.splice(1, 0, 'Steve')
console.log(list)
// [ 'tom', 'Steve', 'Jack' ]