Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Chèn phần tử vào array tại index cụ thể trong JavaScript

1. Cuối mảng: push()

let arr = ["test", 1, 2, "hello", 23.5];
arr.push(123);
console.log(arr); // ['test', 1, 2, 'hello', 23.5, 123]

2. Đầu mảng: unshift()

arr.unshift(123);
console.log(arr); // [123, 'test', 1, 2, 'hello', 23.5]

3. Vị trí bất kỳ: splice()

arr.splice(startIndex, deleteCount, ...items)

let arr = ["test", 1, 2, "hello", 23.5];
// Chèn 123 tại index 2, xóa 0 phần tử
arr.splice(2, 0, 123);
console.log(arr); // ['test', 1, 123, 2, 'hello', 23.5]

Tóm tắt

  • push: cuối
  • unshift: đầu
  • splice(index, 0, item): giữa (deleteCount=0 = insert only)