Array.prototype.slice && Array.prototype.splice 用法阐述

目的

对于这两个数组操作接口,由于不理解, 往往被误用, 或者不知道如何使用。本文尝试给出容易理解的阐述。

数组

什么是数组?

数组是一个基本的数据结构, 是一个在内存中依照线性方式组织元素的方式, 其中元素的类型必须是相同的, 这个每个元素的索引地址才能被计算出来, 索引通常是数字,用来计算元素之间存储位置的偏移量。

结构如下:

http://img.blog.csdn.net/20141202213158497?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGF3YW5nYW5iYW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center

javascript数组

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

javascript中 Array 是一个对象, 而且是全局对象, 用于创建实际的数组, 数组是一种类似链表的对象。

创建数组:

var fruits = ["Apple", "Banana"];

console.log(fruits.length);
// 2

利用index访问数组元素:

var first = fruits[0];
// Apple

var last = fruits[fruits.length - 1];
// Banana

遍历数组元素:

fruits.forEach(function (item, index, array) {
  console.log(item, index);
});
// Apple 0
// Banana 1

向数组后添加元素:

var newLength = fruits.push("Orange");
// ["Apple", "Banana", "Orange"]

从数组尾部删除元素:

var last = fruits.pop(); // remove Orange (from the end)
// ["Apple", "Banana"];

从数组头部删除元素:

var first = fruits.shift(); // remove Apple from the front
// ["Banana"];

添加元素到数组头部:

var newLength = fruits.unshift("Strawberry") // add to the front
// ["Strawberry", "Banana"];

查找元素的索引号:

fruits.push("Mango");
// ["Strawberry", "Banana", "Mango"]

var pos = fruits.indexOf("Banana");
// 1

使用索引号删除元素:

var removedItem = fruits.splice(pos, 1); // this is how to remove an item
// ["Strawberry", "Mango"]

拷贝数组:

var shallowCopy = fruits.slice(); // this is how to make a copy
// ["Strawberry", "Mango"]

创建数组的语法:

Syntax

[element0, element1, ..., elementN]
new Array(element0, element1[, ...[, elementN]])
new Array(arrayLength)
elementN
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number. (See below.) Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
arrayLength
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number. If the argument is any other number, a RangeError exception is thrown.

Array.prototype.slice

slice 英文翻译:

http://www.iciba.com/slice/

原意为 一块面包 切下来的 薄片。

N-COUNT (指食物切下的)片,薄片 A slice of bread, meat, fruit, or other food is a thin piece that has been cut from a larger piece. 

  • Try to eat at least four slices of bread a day.

    每天尽量至少吃 4 片面包。

  • ...water flavored with a slice of lemon.

    加了一片柠檬调味的水

引申意为 整体中的 一部分。

N-COUNT 部分;份 You can use slice to refer to a part of a situation or activity. 

  • Fiction takes up a large slice of the publishing market.

    小说在出版市场上占了很大的份额。

  • ...a car that represents a slice of motoring history.

    一辆代表了一段汽车发展史的轿车

结合数组的定义, 此接口是从  数组中 切下来 一部分, 或者成为一片, 可能片的长度有点大就成为一段。

例如从这个数组中

image

slice 切出一部分:

image

MDN定义

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

The slice() method returns a shallow copy of a portion of an array into a new array object. 【注意:这里面说的是浅拷贝】

Syntax

arr.slice([begin[, end]])

Parameters

begin
Zero-based index at which to begin extraction.
As a negative index, begin indicates an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.
If begin is omitted, slice begins from index 0.
end
Zero-based index at which to end extraction. slice extracts up to but not including end.
slice(1,4) extracts the second element up to the fourth element (elements indexed 1, 2, and 3).
As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.
If end is omitted, slice extracts to the end of the sequence (arr.length).

说明:

1、 浅拷贝

2、 slice() 无入参, 则拷贝整个数组

3、 slice(begin),只有开始入参, 即end省略, 则表示 从begin到arr.length元素都取得。

4、 slice(begin, end) 取得下标为 [begin, end-1] 的元素。

5、 begin 或者 end为负值,则表示从数组后端开始计数。

例子:

// Our good friend the citrus from fruits example
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

// citrus contains ['Orange','Lemon']

Array.prototype.splice

splice:

http://www.iciba.com/splice/

VERB 绞接(绳子);粘接(胶片、磁带等) If you splice two pieces of rope, film, or tape together, you join them neatly at the ends so that they make one continuous piece. 

  • He taught me to edit and splice film...

    他教我剪辑和粘接胶片。

  • The film will be spliced with footage of Cypress Hill to be filmed in America.

    这部电影要和将在美国拍摄的柏树山乐队的音乐片段粘接在一起。

绞接(绳子);粘接(胶片、磁带等)

image

将 两段 影片 或者绳子, 使用胶结 或者 绞接 的方式, 将其连接起来, 其连接部位称为 胶结处、 绞接处 ,  即为

splice

作为动词, 就是  绞接、 胶结(连接两段相同的长条状物体)。

但是搜索splice图片, 会出现很多一部电影相关的图片(中文 人兽杂交 英文名为 splice):

这个故事, 是说两个科学家, 违反科学道德, 利用人类基因和兽类基因, 做杂交试验, 生产出一个新的物种, 这个物种就是 杂交(splice), 此杂交是基因序列的 拼接, 进而产生杂交的结果, 产生个人不人,兽不兽的物体。

Splice-poster.jpg

可以想象基因是一条长长的链条, 基因链条中 基因组排列 决定了 生命的特征, 人的生老病死都是由他决定。

splice电影中, 基因条拼接的意思, 猜测工作应该是这样, 将人类的基因条中, 挖掉某一段(slice), 补上兽类的基因一小段, 这个补的动作,就是拼接 splice。

image

MDN定义

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

注意splice函数,改变现有数组内容, 其功能包括 删除元素 和 添加元素。

Syntax

array.splice(start, deleteCount[, item1[, item2[, ...]]])
Parameters
start
Index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.
deleteCount
An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.
itemN
The element to add to the array. If you don't specify any elements, splice() will only remove elements from the array.
Returns

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

说明:

1、 splice 接口 改变现有数组内容。

2、 splice 可以删除元素 和 添加元素。  <<---- 功能衍生于 splice电影。

删除和添加 正体现了拼接的要素, 删除-破坏了现有数组,破坏之后需要进行修补,

修补的结果就是拼接新的数组段,splice 拼接新的数组段, 合并到现有数组中。

这两个步骤, 多么类似 电影人兽杂交中基因拼接的标准步骤 (挖掉人类基因中坏的部分, 在这个位置上不上兽类的良好基因), 怀疑js这个接口的定义这, 是收到splice这个电影的启发。 否则按照英文定义, splice只有拼接的含义, 没有挖掉的含义, 不应该在此接口中实现挖掉的功能。

3、splice(begin, count), 表示从begin位置开始删除count个元素。

       begin为负值表示从数组尾部向前计数。

       如果 count大于数组的从begin位置计算的元素个数, 则到结束所有的元素都将被删除。

4、splice(begin, 0, itema), 表示在begin位置后面添加itema元素。

5、splice(begin, 1, itema, itemb), 全功能用法, 在begin位置开始删除一个元素, 然后在删除元素的位置替换上元素  itema 和 itemb。

6、 splice 返回 删除元素的 数组。

例子:

var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed

// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']

// removes 1 element from index 2, and inserts 'trumpet'
removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']

// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']

// removes 2 elements from index 3
removed = myFish.splice(3, Number.MAX_VALUE);
// myFish is ['parrot', 'anemone', 'blue']
// removed is ['trumpet', 'surgeon']
原文地址:https://www.cnblogs.com/lightsong/p/4774458.html