Array.prototype.slice && Array.prototype.splice Usage Explained

Source: Internet
Author: User
Tags javascript array

Objective

For these two array operators, they are often misused or unaware of how they are used because they are not understood. This article attempts to give an easy-to-understand explanation.

Array

What is an array?

An array is a basic data structure, a way of organizing elements in memory in a linear manner, where the type of the element must be the same, and the index address of each element can be computed, and the index is usually a number used to calculate the offset of the storage location between the elements.

The structure is as follows:

JavaScript arrays

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

In JavaScript, an array is an object and a global object that creates an actual array, which is a list-like object.

To create an array:

var fruits = ["Apple", "Banana"];console.log(fruits.length);// 2

To access an array element using index:

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

To iterate over an array element:

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

Add elements to the array:

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

To delete an element from the tail of an array:

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

To delete an element from the head of an array:

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

To add an element to the array header:

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

Find the index number of an element:

fruits.push("Mango");// ["Strawberry", "Banana", "Mango"]var pos = fruits.indexOf("Banana");// 1

To delete an element using an index number:

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

Copy an array:

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

Syntax for creating an array:
Syntax
[element0element1elementN]new Array(element0element1elementN]])new Array(arrayLength)
elementN
A JavaScript array is initialized with the given elements, except in the case where a single argument are passed to the Arrayconstructor and that argument is a number. (see below.) Note that this special case only applies to JavaScript arrays created Array with the constructor, not array literals CR Eated with the bracket syntax.
arrayLength
If The only argument passed Array to the constructor are an integer between 0 and 232-1 (inclusive), this returns A new JavaScript array with the length set to that number. If The argument is any and number, a RangeError exception is thrown.
Array.prototype.sliceslice English translation:

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

A slice of bread that was originally intended to be sliced.

N-count (refers to food cut) slices, flakes A slice of bread, meat, fruit, or other foods is A thin piece that have been cut from a larger Piece.

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

    Try to eat at least 4 slices of bread every day.

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

    With a slice of lemon-flavored water.

Extension means a part of the whole.

N-count parts; You can use the slice to refer to a part of a situation or activity.

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

    The novel occupies a large share in the publishing market.

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

    A car that represents the history of a car

In conjunction with the definition of an array, this interface is cut off from the array, or becomes a piece, and the length of the piece may be a bit large.

For example, from this array

Slice cut out part:

MDN definition

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. "Note: This is a shallow copy."

Syntax
arr.slice([beginend]])
Parameters
begin
zero-based index at which to begin extraction.
as a negative index, indicates an offset from the end of the begin sequence. Extracts the last of the elements in the slice(-2) sequence.
If begin is omitted, slice begins from index 0 .
end
zero-based index at which to end extraction. Extracts up and not slice including end .
slice(1,4) extracts the second element up to the fourth element (elements indexed 1, 2, and 3).
as a negative index, indicates an offset from the end of the end sequence. slice(2,-1)extracts the third element through the Second-to-last element in the sequence.
If end is omitted, extracts to the end of the slice sequence ( arr.length ) .

Description

1. Shallow copy

2, Slice () No entry, copy the entire array

3, slice (begin), only the start entry, that is, end omitted, is obtained from the begin to the arr.length element.

4. Slice (begin, end) gets the element labeled [begin, End-1].

5, begin or end is negative, it means counting from the back end of the array.

Example:

// Our good friend the citrus from fruits examplevar fruits = [‘Banana‘, ‘Orange‘, ‘Lemon‘, ‘Apple‘, ‘Mango‘];var citrus = fruits.slice(1, 3);// citrus contains [‘Orange‘,‘Lemon‘]
Array.prototype.splicesplice:

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

VERB stranding (rope); bonding (film, tape, etc.) If you splice -pieces of rope, film, or tape together, you join them neatly at the ends So, they make one continuous piece.

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

    He taught me to clip and glue the film.

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

    The film is to be glued together with the music footage of the Cypress Mountain band that will be filmed in the United States.

To splice (a rope); Bond (film, tape, etc.)

Two pieces of film or rope, the use of cementation or stranding the way, connect it, the connection part is called cementation, stranding Place, that is,

Splice

As a verb, it is twisted, cemented (connecting two pieces of the same strip).

But search splice pictures, there will be a lot of movie-related pictures (Chinese man-beast hybrid English named splice):

The story is that two scientists, contrary to scientific ethics, use the human gene and the beast gene, do the hybridization experiment, to produce a new species, this species is a hybrid (splice), this hybridization is the mosaic of genetic sequences, resulting in the result of hybridization, resulting in the individual, animal not beast objects.

It can be imagined that the gene is a long chain, the gene chain in the genome arrangement determines the characteristics of life, people's illness and death are determined by him.

Splice film, The meaning of the gene strip splicing, guess the work should be so, the human genome, dug out a section (slice), fill the animal's genes a small section, the complement of the action, is splicing splice.

MDN definition

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

Note the splice function, which changes the contents of an existing array, including deleting elements and adding elements.

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

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

Description

1, the Splice interface changes the existing array contents.

2. Splice can delete elements and add elements. <<----features are derived from splice movies.

deleting and adding features that embody stitching, delete-destroys an existing array and requires patching after it is destroyed.

The result of patching is stitching new array segments, splice stitching new array segments and merging them into existing arrays.

These two steps, how similar to the standard step of gene splicing in a filmmaker's hybrid (digging out the bad parts of the human genome, not the good genes of the beast in this position), the suspicion of this interface is the definition of JS this is to receive splice this movie inspired. Otherwise, according to the definition of English, splice only the meaning of stitching, no digging out of the meaning, should not be implemented in this interface to dig out the function.

3, splice (begin, Count), which represents the deletion of count elements starting from the begin position.

Begin is a negative value that counts forward from the tail of the array.

If count is greater than the number of elements calculated from the begin position of the array, all elements to the end will be deleted.

4, splice (begin, 0, Itema), which indicates that the Itema element is added after the begin position.

5, splice (begin, 1, Itema, ITEMB), full-featured usage, begins by deleting an element at begin position and substituting the element Itema and Itemb at the location where the element was deleted.

6. Splice returns an array of deleted elements.

Example:

  var myFish = [' Angel ', ' clown ', ' Mandarin ', ' surgeon '];//removes 0 elements from index 2, and inserts ' Drum ' VA  R removed = Myfish.splice (2, 0, ' drum ');//MyFish is [' Angel ', ' clown ', ' drum ', ' Mandarin ', ' surgeon ']//removed are [], no Elements removed//removes 1 element from index 3removed = Myfish.splice (3, 1);//MyFish is [' Angel ', ' clown ', ' drum ', ' s Urgeon ']//removed is [' Mandarin ']//removes 1 element from index 2, and inserts ' trumpet ' removed = Myfish.splice (2, 1, ' t Rumpet ');//MyFish is [' Angel ', ' clown ', ' trumpet ', ' Surgeon ']//removed are [' drum ']//removes 2 elements from index 0, an  D 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 3removed = Myfis H.splice (3, Number.MAX_VALUE);//MyFish is [' Parrot ', ' anemone ', ' blue ']//removed are [' trumpet ', ' Surgeon ']  

Array.prototype.slice && Array.prototype.splice Usage Description

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.