[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/splice [Back]  [Original]

Array.prototype.splice() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Array.prototype.splice()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 20157.

splice()

In this article

const months = ["Jan", "March", "April", "June"];
months.splice(1, 0, "Feb");
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, "May");
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]

js
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

start

0 -1 0

deleteCount

deleteCount array.length - start deleteCount start start deleteCount 0

item1, item2, ...

start splice() start deleteCount

2 0 drum

js
var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(2, 0, "drum");

// myFish  ["angel", "clown", "drum", "mandarin", "sturgeon"]
// removed  [], 

3 1

js
var myFish = ["angel", "clown", "drum", "mandarin", "sturgeon"];
var removed = myFish.splice(3, 1);

// removed  ["mandarin"]
// myFish  ["angel", "clown", "drum", "sturgeon"]

2 1 trumpet

js
var myFish = ["angel", "clown", "drum", "sturgeon"];
var removed = myFish.splice(2, 1, "trumpet");

// myFish  ["angel", "clown", "trumpet", "sturgeon"]
// removed  ["drum"]

0 2 parrotanemoneblue

js
var myFish = ["angel", "clown", "trumpet", "sturgeon"];
var removed = myFish.splice(0, 2, "parrot", "anemone", "blue");

// myFish  ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed  ["angel", "clown"]

2 2

js
var myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"];
var removed = myFish.splice(myFish.length - 3, 2);

// myFish  ["parrot", "anemone", "sturgeon"]
// removed  ["blue", "trumpet"]

-2 1

js
var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(-2, 1);

// myFish  ["angel", "clown", "sturgeon"]
// removed  ["mandarin"]

2 2

js
var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(2);

// myFish  ["angel", "clown"]
// removed  ["mandarin", "sturgeon"]

Specification
ECMAScript 2027 LanguageSpecification
# sec-array.prototype.splice

  • push() / pop() add/remove elements from the end of the array
  • unshift() / shift() add/remove elements from the beginning of the array
  • concat() returns a new array comprised of this array joined with other array(s) and/or value(s)

Web Proxy Viewer  |  New URL  |  Original Page