The method of adding elements at the head of the array in JS

1. Use the Array.unshift() method to insert elements at the head of the array

let person= ['张三', '李四', '王五'];
console.log(person.unshift('小明')); // 4
console.log(person); // ["小明", "张三", "李四", "王五"]
// 注意: 此方法的返回值是数组的长度 且改变原数组

2. Using the ES6 spread operator (...)

// 定义一个数组
let arr = ['张三', '李四']
let arr2 = ['王五', ...arr]
console.log(arr2) // 王五 张三 李四
// 定义一个数组,在头部写好需要插入的项后使用扩展运算符对原数组进行展开

3. Use the Array.contact method to splice the array

// contact方法连接两个或多个数组
let arr1 = ['前端', 'JAVA']
let arr2 = ['攻城狮', '程序猿'] // 需添加在头部的元素
console.log(arr2.contact(arr1)) // 攻城狮 程序猿 前端 JAVA
// 注: contact方法不改变原数组

Supongo que te gusta

Origin blog.csdn.net/qq_27158739/article/details/127281143
Recomendado
Clasificación