要在数组末尾插入,我们可以使用push方法。为了在数组的开头插入,我们可以使用unshift方法。要在其他位置插入,可以使用splice方法。
让我们看一下每个例子-
推-
let arr = ["test", 1, 2, "hello", 23.5]; arr.push(123); console.log(arr);
输出结果
[ 'test', 1, 2, 'hello', 23.5, 123 ]
换档-
let arr = ["test", 1, 2, "hello", 23.5]; arr.unshift(123); console.log(arr);
输出结果
[ 123, 'test', 1, 2, 'hello', 23.5 ]
拼接-
该splice()
方法通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容。我们可以通过以下方式使用它在给定索引处插入元素-
let arr = ["test", 1, 2, "hello", 23.5]; //用123替换0个元素(也可以被解释为插入)在索引2 arr.splice(2, 0, 123); console.log(arr);
输出结果
[ 'test', 1, 123, 2, 'hello', 23.5 ]