JavaScript

js中splice()详解(插入、删除或替换数组的元素)

2020-01-08  本文已影响0人  西瓜鱼仔

处理数组的方法很多,javascript 的splice() 算是最强大的了,它可以用于插入、删除或替换数组的元素。

  1. 删除:用于删除元素,两个参数,第一个参数(要删除第一项的位置),第二个参数(要删除的项数)
Remove 1 element from index 3
var myFish = ["angel", "clown", "drum", "mandarin", "surgeon"];
var removed = myFish.splice(3, 1);

// removed is ["mandarin"]
// myFish is ["angel", "clown", "drum", "surgeon"]
  1. 插入:向数组指定位置插入任意项元素。三个参数,第一个参数(其实位置),第二个参数(0),第三个参数(插入的项)
Remove 0 elements from index 2, and insert "drum"
var myFish = ["angel", "clown", "mandarin", "surgeon"];
var removed = myFish.splice(2, 0, "drum");

// myFish is ["angel", "clown", "drum", "mandarin", "surgeon"] 
// removed is [], no elements removed

3.替换:向数组指定位置插入任意项元素,同时删除任意数量的项,三个参数。第一个参数(起始位置),第二个参数(删除的项数),第三个参数(插入任意数量的项)

Remove 1 element from index 2, and insert "trumpet"
var myFish = ["angel", "clown", "drum", "surgeon"];
var removed = myFish.splice(2, 1, 'trumpet');

// myFish is ["angel", "clown", "trumpet", "surgeon"]
// removed is ["drum"]

原文地址 https://my.oschina.net/yangchunlian/blog/809198

上一篇下一篇

猜你喜欢

热点阅读