preface

In the next article, we will take a detailed look at the contents of the JS array. This section covers “operations involving data elements, as well as the splitting and concatenation of arrays”, the previous portal


push()

Push () : Inserts one or more elements to the back of the array, returning the length of the new array. It changes the original array, because the original array becomes the new array.

Syntax: Length of new array = array.push (element);

Example:

var arr = ['a king'.'the king 2'.'three'];
var result1 = arr.push('the king of four'); // Insert an element at the end
var result2 = arr.push('Cathy'.'king of six'); // Insert multiple elements at the end
console.log(result1); // Print the result: 4
console.log(result2); // Print the result: 6
console.log(JSON.stringify(arr)); // Print result: [" wang1 "," Wang2 "," Wang3 "," Wang4 "," Wang5 "," Wang6 "]
Copy the code

pop()

Pop () : Removes the last element in the array, returning the deleted element.

Syntax: Removed element = array. Pop ();

Example:

var arr = ['a king'.'the king 2'.'three'];
var result1 = arr.pop();
console.log(result1); // Print the result: Wang3
console.log(JSON.stringify(arr)); // Print result: [" wang yi "," Wang Yi "]
Copy the code

unshift()

Unshift () : Inserts one or more elements at the front of the array, returning the length of the new array. It changes the original array, because the original array becomes the new array. After an element is inserted, the indexes of other elements are adjusted in turn.

Syntax: Length of new array = array.unshift (element);

Example:

var arr = ['a king'.'the king 2'.'three'];
var result1 = arr.unshift('the king of four'); // Insert an element first
var result2 = arr.unshift('Cathy'.'king of six'); // Insert more elements first
console.log(result1); // Print the result: 4
console.log(result2); // Print the result: 6
console.log(JSON.stringify(arr)); // Print result: [" Wangwu "," Wang6 "," Wang4 "," Wang1 "," Wang2 "," Wang3 "]
Copy the code

shift()

Shift () : Deletes the first element in the array, returning the deleted element.

Syntax: Removed element = array. Shift ();

Example:

var arr = ['a king'.'the king 2'.'three'];
var result1 = arr.shift();
console.log(result1); // Print the result: Wang Yi
console.log(JSON.stringify(arr)); // Print result: [" wang2 "," Wang3 "]
Copy the code

Summary:

  • Push and unshift have the same effect, except that push is back and unshift is front
  • Pop is the same as Shift, but pop is the back delete, shift is the front delete

slice()

Slice () : Extracts one or more specified elements from an array, returning a new array (without changing the original array).

Note: this method does not alter the original array, but returns the intercepted elements wrapped in a new array.

Syntax: New array = original array. Slice (start index, end index);

Note: startIndex is included,endIndex is not included, i.e. range is [startIndex,endIndex]

For example:

const arr = ['a'.'b'.'c'.'d'.'e'.'f'];
const result1 = arr.slice(); // Get all elements without arguments. Equivalent to a global assignment of an array
const result2 = arr.slice(2); // Start extracting from the second value until the end
const result3 = arr.slice(-2); // Extract the last two elements
const result4 = arr.slice(2.4); // Extract elements from the second to the fourth (excluding the fourth element)
const result5 = arr.slice(4.2); / / empty

console.log('arr:' + JSON.stringify(arr));
console.log('result1:' + JSON.stringify(result1));
console.log('result2:' + JSON.stringify(result2));
console.log('result3:' + JSON.stringify(result3));
console.log('result4:' + JSON.stringify(result4));
console.log('result5:' + JSON.stringify(result5));
Copy the code

Print result:

arr: ['a'.'b'.'c'.'d'.'e'.'f'];
result1: ['a'.'b'.'c'.'d'.'e'.'f'];
result2: ['c'.'d'.'e'.'f'];
result3: ['e'.'f'];
result4: ['c'.'d'];
result5: [];
Copy the code

Supplement:

Many front-end developers use slice() to convert pseudo-arrays into real arrays. It is written as follows:

1 / / way
array = Array.prototype.slice.call(arrayLike);
2 / / way
array = [].slice.call(arrayLike);
Copy the code

ES6 couldn’t stand this crappy conversion, so a new API was created: Array.from(),

array = Array.from(arrayLike);
Copy the code

For a more detailed introduction to this API, please scroll forward.


splice()

Splice () : Deletes one or more specified elements from an array, returning a new array of the deleted elements (changing the original array).

Note: This method alters the array, removing the specified element from the array, and returning the deleted element in a new array.

Grammar:

arrayObject.splice(index,howmany,item1,..... ,itemX)Copy the code

Expected effect:

  • Delete (basic)

    New array = old array.splice (start index, number to delete);

  • Add elements

    New array = old array.splice (index, number to delete (set to 0), new element 1, new element 2…) ;

  • Replace (by adding extensions)

    Splice (start index index, number of elements to delete (number of elements to be replaced), new element 1, new element 2…) ;

  • Delete replacement exists at the same time

    Control the number of delete can be achieved

In the preceding syntax, the third and subsequent arguments indicate that after an element is deleted, new elements are added to the original array, and these elements are automatically inserted before the starting position index. It can also be interpreted as: delete the elements, add new content in the place of those elements.

The slice() and splice() methods can easily be confused, so be careful to distinguish them.

Example 1:

var arr1 = ['a'.'b'.'c'.'d'.'e'.'f'];
var result1 = arr1.splice(1); // Delete the element starting at index 1

console.log('arr1:' + JSON.stringify(arr1));
console.log('result1:' + JSON.stringify(result1)); Results ARr1: ["a"] result1: ["b"."c"."d"."e"."f"]
Copy the code

Example 2 :(let’s see how the third parameter is used)

var arr4 = ['a'.'b'.'c'.'d'.'e'.'f'];
// Delete elements from index 1. And append two elements to index=1
var result4 = arr4.splice(1.3.'A little front siege lion.'.'vae');

console.log('arr4:' + JSON.stringify(arr4));
console.log('result4:' + JSON.stringify(result4)); Results ARR4: ["a"."A little front siege lion."."vae"."e"."f"] result4: ["b"."c"."d"]
Copy the code

fill()

Fill () : Fills an array with a fixed value and returns a new array. It doesn’t change the original array.

Grammar:

// Fill the array with a fixed value. Every element in the array will be filled with this fixed valueNew array = array. Fill (fixed value);// Array elements starting with startIndex, filled with fixed valuesNew array = array. Fill (fixed value, startIndex);// The element from startIndex to endIndex (left, not right) is filled with fixed valuesNew array = array. Fill (fixed, startIndex, endIndex);Copy the code

For example:

// Create an empty array of length 4 and fill it with 'f'
console.log(Array(4).fill('f')); // ['f', 'f', 'f,' 'f']

// Populates each element of the existing array
console.log(['a'.'b'.'c'.'d'].fill('f')); // ['f', 'f', 'f,' 'f']

// Specify the location to fill
console.log(['a'.'b'.'c'.'d'].fill('f'.1.3)); // ["a", "f", "f", "d"]
Copy the code