JavaScript array

Time:2020-10-31

JavaScript array

Arrays are reference types. Everything in JavaScript is an object.
An array element can be a string, number, array, Boolean, or other object type.

Array creation

1. Use array literal

let arr0 = [1, "array", true, Date.now()];

2. Use the constructor array ()

Let arra1 = new array(); // equivalent to []
Let arrar2 = new array (1, 2, 3, "array"); // display the specified
Let arrar3 = new array (10); // specify the length

Properties of the array

attribute describe
length Sets or returns the number of array elements
constructor Returns the prototype function that creates an array object
prototype Add a property or method to an array object

Array method

JavaScript array

Will change their own way

  • pop()

Function: used to delete the last element of the array and return the deleted element.
Parameter: None
Return value: returns the deleted element

let arr = [2, 4, 6, 'a', 8, true, 9];
arr.pop();
console.log(arr);//[ 2, 4, 6, 'a', 8, true ]
  • push()

function: adds one or more elements to the end of the array and returns the new length.
parameter:push(newData1, newData2, ……)
Return value: new array length

let arr = [2, 4, 6, 'a', 8, true, 9];
arr.push("c");
console.log(arr);//[ 2, 4, 6, 'a', 8, true, "c" ]
  • shift()

function: used to delete and return the first element of an array.
parameter: none

let arr = [2, 4, 6, 'a', 8, true, 9];
console.log(arr.shift());//2
console.log(arr);//[ 4, 6, 'a', 8, true, 9 ]
  • unshift()

function: adds one or more elements to the beginning of the array and returns the new length.
parameter:unshift(newData1, newData2, ……)

let arr = [2, 4, 6, 'a', 8, true, 9];
arr.unshift(()=>{});
console.log(arr);//[ [Function], 2, 4, 6, 'a', 8, true, 9 ]
  • reverse()

function: reverses the order of elements in an array and returns the changed array
parameter: none

let arr = [2, 6, 'a', 8, true, 9];
arr.reverse();
console.log(arr);//[ 9, true, 8, 'a', 6, 2 ]
  • sort()

function: sort the elements in the array, the default is ascending, and return the new array
parameter: none
be careful: before sorting, thetoString()Method: after each element is converted into a character, it is sorted. At this time, it is sorted by string, bit by bit comparison.

let arr = [2, 16, 'a', 8, true, 9];
arr.sort();
console.log(arr);//[ 16, 2, 8, 9, 'a', true ]

resolvent: by passing in a custom function. sort(fn)
If the FN (a, b) function returns a negative number, thenabe ranked atbfront.
If the FN (a, b) function returns a negative number, thenbbe ranked atafront.

function fnS_ B (a, b) {// from small to large
    return a-b;
}
function fnB_ S (a, b) {// from large to small
    return b-a;
}
//Note: number ('a ') is Nan and cannot be used for sorting.
let arr = [2, 16,  8, true, 9];
console.log(arr.sort(fnS_B));
console.log(arr.sort(fnB_S));
  • splice()

function: add to, remove from, or replace elements in an array, and then return the deleted / replaced elements. The length of the array does not change before and after.
parameter: split (start, num, data1, data2,…); all parameters are optional; it can be divided into many cases

  • start: integer, which specifies the index of the position of adding / deleting items. Use negative numbers to specify the position of deletion from the end of the array
  • num: integer, which specifies the number of elements to be deleted. If it is 0, it will not be deleted
  • data1,data2,data3…..: optional, specifies the elements to be added
let arr = [2, 8, true, 9];
arr.splice(1, 0, 'a', 'b');
console.log(arr);//[ 2, 'a', 'b', 8, true, 9 ]
arr.splice(1,2,16);  
console.log(arr);//[ 2, 16, 8, true, 9 ]
  • copyWithin() #ES6

function: copies elements from the specified position of the array to another specified position of the array. And returns the new array.
parameter:array.copyWithin(target, start, end)

  • target: required. Copy to the specified target index location.
  • start: optional. The starting position of the element copy. Default start = 0.
  • end: optional. Index location where replication is stopped (default is array.length )。 If it is negative, it means the reciprocal.

Note: the copied elements are [start, end]

let arr = [2, 8, 'a', true, 9];
console.log(arr.copyWithin(1, 2, 4));//[ 2, 'a', true, true, 9 ]
  • fill #ES6

function: used to replace an element of an array with a fixed value.
parameter:array.fill(value, start, end)

  • target : required. Copy to the specified target index location.
  • start: optional. The starting position of the element copy. Default start = 0.
  • end: optional. Index location where replication is stopped (default is array.length )。 If it is negative, it means the reciprocal.

Note: the copied elements are [start, end]

let arr = [2, 8, 'a', true, 9];  
console.log(arr.fill(6, 1, 3));//[ 2, 6, 6, true, 9 ]

Don’t change your way

These methods all return the result of the operation

  • concat()

function: used to join two or more arrays. This method does not change the existing array, but only returns a copy of the joined array.
parameter:array1.concat(array2,array3,…,arrayX)

let arr1= [1,'a',false];
let arr2=[2,'b',true];
console.log(arr1.concat(arr2));//[ 1, 'a', false, 2, 'b', true ]
  • join()

functionThe: join() method is used to convert all elements in an array into a string and return the string. Elements are separated by the specified separator.
parameter:array.join(separator)

separator: optional. Specifies the separator to use. If the parameter is omitted, a comma is used as the separator.

let arr = [2, 8, 'a', true, 9];
console.log(arr.join('-')); //2-8-a-true-9
  • slice()

function: returns the selected element from an existing array. The slice() method extracts a part of a string and returns the extracted part with a new string.
parameter:slice(start, end)

  • start: optional. Specify where to start the selection.
  • end: optional. Specify where to end the selection.

Note: select the element as [start, end]

let arr = [2, 8, 'a', true, 9];
console.log(arr.slice()); //[ 2, 8, 'a', true, 9 ]
console.log(arr.slice(1, 3)); //[ 8, 'a' ]
  • toString()

function: converts an array to a string and returns the result. Elements in the array are separated by commas.
parameter: none.

let arr = [2, 8, 'a', true, 9];
console.log(arr.toString()); //2,8,a,true,9
  • indexOf()

function: returns the position of a specified element in an array. If the element to retrieve does not appear, the method returns – 1.
parameter:array.indexOf(item,start)

  • item: required. Element to find.
  • start: optional. Specifies the location in the array where retrieval begins. Default start = 0. Its legal value is 0 to array.length – 1。
let arr = [2, 8, 'a', true, 9];
console.log(arr.indexOf(8)); // 1
console.log(arr.indexOf(9, 2)); // 4
console.log(arr.indexOf(8, -1)); //
  • lastIndexOf()

function: returns the last position of a specified element in the array, looking forward from the back of the string. If the element to retrieve does not appear, the method returns – 1.
parameter:array.lastIndexOf(item,start)

  • item: required. Element to find.
  • start: optional. Specifies the location in the array where retrieval begins. The default start = – 1.
let arr = [2, 8, 'a', 8,true, 9];
console.log(arr.lastIndexOf(8, 1)); // 1
console.log(arr.lastIndexOf(8)); // 3
  • includes() #ES7

function: used to determine whether an array contains a specified value. If yes, it returns true, otherwise false.
parameter:arr.includes(item, start)

  • item: required. Element to find.
  • start: optional. Specifies the location in the array where retrieval begins. Default start = 0. If it is a negative value, it is sorted in ascending order from array.length +The index of start starts the search.

Note the difference from indexof().

let arr = [2, 8, 'a', true, 9];
console.log(arr.includes(8));  //true
console.log(arr.includes(8, 2));  //false
console.log(arr.includes(8, -2));  //false

traversal method

  • forEach()

function: used to call each element of the array and pass the element to the callback function. Empty arrays are not detected.
parameter:array.forEach(function(currentValue, index, arr), thisValue)

  • function(currentValue, index, arr): required. The function to be called for each element in the array.

    • currentValue: required. Current element.
    • index: optional. The index value of the current element.
    • arr: optional. The array object to which the current element belongs.
  • thisValue: optional. Use as the value of this when executing the callback function. The default value is undefined
//Adds all elements of the array
let sum = 0;
function add(item){
    sum+=item;
}
let arr = [1,3,8,6];
arr.forEach(add);
console.log(sum); //18
  • map()

function1. Same as foreach function;
2. Return a new array. The elements in the array are the values processed by calling the function of the original array elements.
3. The original array does not change.
parameter:array.map(function(currentValue,index,arr), thisValue)

  • function(currentValue, index, arr): required. The function to be called for each element in the array.

    • currentValue: required. Current element.
    • index: optional. The index value of the current element.
    • arr: optional. The array object to which the current element belongs.
  • thisValue: optional. Use as the value of this when executing the callback function. If thisvalue is omitted, or null or undefined is passed in, this of the callback function is the global object.
//Square the output array
function fn(item) {
    return item * item;
}

let arr = [6, 2, 8, 5];
console.log(arr.map(fn)); //[ 36, 4, 64, 25 ]
  • filter()

function: creates a new array. The elements in the new array specify all the elements in the array that meet the criteria. If there are no eligible elements, an empty array is returned.
parameter:array.filter(function(currentValue,index,arr), thisValue)

  • function(currentValue, index, arr): required. The function to be called for each element in the array. Must return a Boolean value.

    • currentValue: required. Current element.
    • index: optional. The index value of the current element.
    • arr: optional. The array object to which the current element belongs.
  • thisValue: optional. Use as the value of this when executing the callback function. The default value is undefined
//Even number in output array
function fn(item) {
    if (item % 2) {
        return false;
    } else {
        return true;
    }
}
let arr = [6, 2, 8, 5];
console.log(arr.filter(fn)); //[ 6, 2, 8 ]
  • every()

function: used to detect whether all elements of the array areallMeet the specified conditions. Returns true if all elements pass detection, false otherwise.
parameter:array.every(function(currentValue,index,arr), thisValue)

  • function(currentValue, index, arr): required. The function to be called for each element in the array.

    • currentValue: required. Current element.
    • index: optional. The index value of the current element.
    • arr: optional. The array object to which the current element belongs.
  • thisValue: optional. Use as the value of this when executing the callback function. The default value is undefined
//Determine whether the array elements are all even
function fn(item) {
    if (item % 2) {
        return false;
    } else {
        return true;
    }
}
let arr = [6, 2, 8, 5];
console.log(arr.every(fn)); //false
  • some()

function: used to detect whether the elements in the array meet the specified conditions.
The some() method executes each element of the array in turn:

  • If one element meets the condition, the expression returns true and the remaining elements are not detected again.
  • If there are no elements that meet the condition, false is returned.

parameter:array.every(function(currentValue,index,arr), thisValue)

  • function(currentValue, index, arr): required. The function to be called for each element in the array.

    • currentValue: required. Current element.
    • index: optional. The index value of the current element.
    • arr: optional. The array object to which the current element belongs.
  • thisValue: optional. Use as the value of this when executing the callback function. The default value is undefined
//Determine whether there is an odd number in the array
function fn(item) {
    if (item % 2) {
        return true;
    } else {
        return false;
    }
}
let arr = [6, 2, 8, 5];
console.log(arr.some(fn));​ // true
  • reduce()

function: from the first item of the array, execute the function successively for each element in the array, traverse to the end one by one, iterate all the items of the array, and return the calculation result.
parameter:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

  • function(total,currentValue, index,arr): required. The function to be called for each element in the array.

    • total: required. The initial value, or the return value at the end of the calculation.
    • currentValue: required. Current element.
    • currentIndex: optional. The index of the current element.
    • arr: optional. The array object to which the current element belongs.
  • initialValue: optional. The initial value passed to the function
//Adds all elements of the array
function fn(total, item) {
    return total += item;
}

let arr = [1, 3, 8, 6];
console.log(arr.reduce(fn, 0)); //18
  • reduceRight()

function: from the end of the array, execute a function for each element in the array, traverse to the first element of the array one by one, iterate all items of the array, and return the calculation result. (in reverse order to reduce)
parameter:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

  • function(total,currentValue, index,arr): required. The function to be called for each element in the array.

    • total: required. The initial value, or the return value at the end of the calculation.
    • currentValue: required. Current element.
    • currentIndex: optional. The index of the current element.
    • arr: optional. The array object to which the current element belongs.
  • initialValue: optional. The initial value passed to the function
//Adds all elements of the array
function fn(total, item) {
    return total += item;
}

let arr = [1, 3, 8, 6];
console.log(arr.reduceRight(fn, 0)); // 18
  • find() #ES6

function: returns the value of the first element that passed the test. If there are no qualified elements, undefined is returned
parameter:array.find(function(currentValue, index, arr),thisValue)

  • function(currentValue, index, arr): required. The function to be called for each element in the array.

    • currentValue: required. Current element.
    • index: optional. The index value of the current element.
    • arr: optional. The array object to which the current element belongs.
  • thisValue: optional. Use as the value of this when executing the callback function. The default value is undefined
//Find the first element value greater than 5
function fn(item) {
    return item>5;
}

let arr1 = [1, 3, 8, 6];
console.log(arr1.find(fn)); // 8
let arr2 = [1, 3, 2, 5];
console.log(arr2.find(fn)); // undefined
  • findIndex() #ES6

function: returns the index of the first element value that passed the test. If there are no eligible elements, return – 1
parameter:array.findIndex(function(currentValue, index, arr), thisValue)

  • function(currentValue, index, arr): required. The function to be called for each element in the array.

    • currentValue: required. Current element.
    • index: optional. The index value of the current element.
    • arr: optional. The array object to which the current element belongs.
  • thisValue: optional. Use as the value of this when executing the callback function. The default value is undefined
//Finds the index of the first element value greater than 5
function fn(item) {
    return item>5;
}

let arr1 = [1, 3, 8, 6];
console.log(arr1.findIndex(fn)); // 2
let arr2 = [1, 3, 2, 5];
console.log(arr2.findIndex(fn)); // -1
  • Entries(), keys() and values ()#ES6

function: used to traverse arrays. They all return a traverser object. You can use the for… Of loop to traverse. The only difference is that keys() is the traversal of key names, values() is the traversal of key values, and entries() is the traversal of key value pairs.
parameter: none

let arr = [1, 3];
console.log(arr.keys());
for (let i of arr.keys()) {
    console.log(i);
}
//0
//1
for (let i of arr.values()) {
    console.log(i);
}
//1
//3
for (let [i, elem] of arr.entries()) {
    console.log(i + "--" + elem);
}
//0--1
//1--3

other

  • Extension operator...

function: converts an array into a comma separated sequence of parameters. This operator is mainly used for function calls.

//Extension operator
function add(a, b) {
    return a + b;
}

let arr = [2, 3];
console.log(add(...arr));// 5
  • from() ES6

function: converts class array objects and traversable objects into arrays.
parameter:Array.from(object, fn, thisValue)

  • Object: required, the object to be converted to an array
  • FN: optional, the function to call for each element in the array
  • Thisvalue: optional, this object in mapfunction
let obj ={
    0:'a',
    1:'b',
    2:'c',
    length:3
};
console.log(Array.from(obj));//[ 'a', 'b', 'c' ]
  • of() ES6

function: used to convert a set of values to an array. The main purpose is to make up for the deficiency of array constructor array(). Because the number of parameters is different, the behavior of array() will be different.
parameter:Array.of(element0[, element1[, …[, elementN]]])

Array(); //[]
Array.of(); //[]

Array(3);//[ , , ,]
Array.of(3);//[3]

Array(2, 4);//[2,4]
Array.of(2, 4);//[2,4]

Array application

Array de duplication

  • indexOf()
// indexOf()
function unique(array) {
  let res = [];
  for (let i of arr) {
    if (res.indexOf(i) === -1) {
      res.push(i);
    }
  }
  return res;
}

let arr = [1, 1, "1", true];
console.log(unique(arr)); //[ 1, '1', true ]
  • Object key value pair
function unique(arr) {
  let obj = {};
  let res = [];
  for (let i of arr) {
    if (!obj[i]) {
      obj[i] = true;
      res.push(i);
    }
  }
  return res;
}

let arr = [1, 1, "1", true];
console.log(unique(arr)); //[ 1, true ]
  • set、map ES6
function unique(array){
    return Array.from(new Set(array));
    // return [...(new Set(array))];
}
let arr = [1, 1, "1", true];
console.log(unique(arr)); //[ 1, '1', true ]

Find the maximum value of an array

Static method using math
Math.max();
Math.min();

  • apply()
let arr = [1, 6, 2, 8];
console.log(Math.max.apply(null,arr));//8
console.log(Math.min.apply(null,arr));//1
  • Extension operatorES6
let arr = [1, 6, 2, 8];
console.log(Math.max(...arr)); //8
console.log(Math.min(...arr)); //1

Array disorder

//Array disorder
function fn(){
    return Math.random()-0.5;
}
let arr = [1,2,3,4,5,6];
console.log(arr.sort(fn));

Recommended Today

Let me also summarize the knowledge of nginx

Recently, I want to deeply study the related knowledge of nginx, so I summarize the following contents. Nginx configuration parameters Nginx common commands Nginx variable Virtual host configuration Nginx’s own module Fastcgi related configuration Common functions Load balancing configuration Static and dynamic separation configuration Anti theft chain What is nginx? Nginx is a free, open […]