Skip to content

Commit

Permalink
add examples about using splice to add elements to array (#31705)
Browse files Browse the repository at this point in the history
* add examples about using splice to add elements to array

* remove insertion duplication

* Remove word duplication

* move and enhance unshift and push examples

* adhere linting rules

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* enhance example header

* Apply suggestions from code review

* Update index.md

* Update index.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Joshua Chen <[email protected]>
  • Loading branch information
3 people authored Jan 15, 2024
1 parent 005cc1f commit aff3a68
Showing 1 changed file with 24 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,30 @@ const removed = myFish.splice(2, 0, "drum", "guitar");
// removed is [], no elements removed
```

### Remove 0 (zero) elements at index 0, and insert "angel"

`splice(0, 0, ...elements)` inserts elements at the start of the array like {{jsxref("Array/unshift", "unshift()")}}.

```js
const myFish = ["clown", "mandarin", "sturgeon"];
const removed = myFish.splice(0, 0, "angel");

// myFish is ["angel", "clown", "mandarin", "sturgeon"]
// no items removed
```

### Remove 0 (zero) elements at last index, and insert "sturgeon"

`splice(array.length, 0, ...elements)` inserts elements at the end of the array like {{jsxref("Array/push", "push()")}}.

```js
const myFish = ["angel", "clown", "mandarin"];
const removed = myFish.splice(myFish.length, 0, "sturgeon");

// myFish is ["angel", "clown", "mandarin", "sturgeon"]
// no items removed
```

### Remove 1 element at index 3

```js
Expand Down

0 comments on commit aff3a68

Please sign in to comment.