• 移除元素功能跟 insert 元素功能 Array.prototype.splice()
  • 將 Array 元素toString,並且用 , 隔開 Array.prototype.toString()
  • 從 Array 前面增加元素 Array.prototype.unshift()

Array.prototype.splice()

移除元素功能跟 insert 元素功能。

參數說明

  • start : 第幾個元素開始執行,從 0 開始計算
  • deleteCount : 要移除幾個元素,若沒指定,則移除全部 (optional)
  • item1, item2, … : 要被 insert 的元素 (optional)

回傳值 : 回傳被移除的元素,若沒有元素被移除,則回傳空 Array

insert 元素

splice
  • js
1
2
3
4
5
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var removed = myFish.splice(2, 0, 'drum');

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

移除元素

splice
  • js
1
2
3
4
5
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
var removed = myFish.splice(3, 1);

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

移除元素與 insert 元素

splice
  • js
1
2
3
4
5
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
var removed = myFish.splice(2, 1, 'trumpet');

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

Array.prototype.toString()

將 Array 元素toString,並且用 , 隔開

toString
  • js
1
2
3
var arr = ['a','b',3,{abc : 123}]; 

console.log(arr.toString()); //a,b,3,[object Object]

Array.prototype.unshift()

從 Array 前面增加元素

回傳值 : 回傳增加元素後 Array 的 length

unshift
  • js
1
2
3
4
5
6
7
8
9
10
var arr = [1, 2];

arr.unshift(0); // result of call is 3, the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // = 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-3]);
// arr is [[-3], -2, -1, 0, 1, 2]

參考

參考連結