JS array related knowledge

Posted by rich___ on Sun, 23 Jan 2022 22:17:28 +0100

catalogue

1, What are the common array methods?

2, Method for creating an array

3, Three methods of judging arrays and their differences

1, What are the common array methods?

Answer: push(), pop(), unshift(), shift(), splice, toString, join, concat, slice, reverse, sort() (a function is passed in sort as a parameter)

**Among the above methods, the methods that will not change the array are: * * concat (connecting two or more arrays), slice (intercepting a part of the array), join (), toString ()

Supplement: toString Method will splice an array into a string, separated by ",".
join Method also splices an array into a string, and the middle division method is based on join()Method
join The scope of application is greater than toString,It can replace the latter

**The array methods that will be changed in the above methods are: * * push, pop, unshift, shift, splice (delete / add elements), reverse and sort

1. push (): adds one or more elements to the end of the array, * * and returns the length of the new array** This method changes the original array.

const array=['one','two','three','four'];
const pushResult = array.push('new1','new2');
console.log(pushResult);// 6
console.log(array); //['one','two','three','four','new1','new2']

2. pop (): delete the last element of the array and return the value of the last element. This method changes the original array.

const array=['one','two','three','four'];
const popResult = array.pop();
console.log(popResult);// four
console.log(array);// ['one','two','three']

3. unshift(): adds one or more elements to the beginning of the array, * * and returns the length of the new array** This method changes the original array.

const array=['one','two','three','four'];
const unshiftResult = array.unshift('new1','new2');
console.log(unshiftResult);//6
console.log(array); //['new1','new2','one','two','three','four']

4. shift (): deletes the first element of the array from it and returns the value of the first element. This method changes the original array.

const array=['one','two','three','four'];
const shiftResult=array.shift();
console.log(shiftResult); //one
console.log(array);  // ['two','three','four']

5. Splice (index, howmany, Item1,..., itemx): Add / delete items to / from the array (after index), and then return the deleted array. This method changes the original array.

//Adds an element to a location in the original array
const array=['one','two','three','four'];
array.splice(2,0,'new1');
console.log('array:', array);//['one','two','three','new1','four']
//Delete the element at index 2 and add a new element to replace the deleted element
 const array=['one','two','three','four'];
 array.splice(2,1,'new1');
 console.log('array:', array);//['one','two',new1','four']

6. toString(): converts a logical value into a string and returns the result.

const array=['one','two','three','four'];
const toStringResult = array.toString();
console.log('array:', toStringResult);//'one,two,three,four'

7. join(separator): put all the elements in the array into a string.

const array=['one','two','three','four'];
const joinResult = array.join();
const joinResult1 = array.join('/');
console.log(joinResult);//"one,two,three,four"
console.log(joinResult1);//"one/two/three/four"

8. concat(): used to connect two or more arrays** This method does not change the existing array, * * but only returns a copy of the connected array.

const array=['one','two','three','four'];
const arrar1=['new3','new4'];
const arrar2 = ['new5', 'new6'];
const concatResult1 = array.concat('new1','new2');
const concatResult2 = array.concat(arrar1);
const concatResult3 = array.concat(arrar1, arrar2);
console.log(concatResult1);//['one','two','three','four','new1','new2']
console.log(concatResult2);//['one','two','three','four','new3','new4']
console.log(concatResult3);//['one','two','three','four','new1','new2','new3','new4']
console.log(array);//['one','two','three','four']

9. slice(start, end): intercepts a part of the array. This method does not modify the array, but returns a sub array containing the elements in the arrayObject from start to end (excluding the element).

const array=['one','two','three','four','five','six','seven'];
const sliceResult1 = array.slice(-4,-2);
const sliceResult2 = array.slice(-2);
const sliceResult3 = array.slice(2,6);
const sliceResult4 = array.slice(2);
console.log(sliceResult1); //['four','five'];
console.log(sliceResult2);//['six','seven'];
console.log(sliceResult3);//['three','four','five','six'];
console.log(sliceResult4);//['three','four','five','six','seven'];
console.log(array);//['one','two','three','four','five','six','seven'];

10. reverse(): flipping the array elements will change the original array

const newArray = array.reverse();
console.log(newArray);//[ 'four', 'three', 'two', 'one' ]
console.log(array);//[ 'four', 'three', 'two', 'one' ]

11. sort(): array sorting method, which will change the original array

const arr = [2, 4, 1, 6, 9, 5];
const newarr = arr.sort();//The default is ascending
const newarr1 = arr.sort((a, b) => b - a);//Descending order
console.log(newarr);//[ 1, 2, 4, 5, 6, 9 ]
console.log(newarr1);//[ 9, 6, 5, 4, 2, 1 ]
console.log(arr);//[ 9, 6, 5, 4, 2, 1 ]

2, Method for creating an array

How to judge whether an array is empty

Judge whether the array is empty according to the length of the array; Is the array equal to false

  1. Create an array with new

    var arr=new Array();//An empty array was created
    var arr1=new Array("1" , 2 , {a:1,b:3})//Created a non empty array ['1', 2, {A: 1, B: 3}]
    
  2. Create an array using array literals (that is, only in the form of brackets ([]))

    var arr3=[];//Create an empty array
    var arr4=["1" , 2 , {a:1,b:3}]Created a non empty array["1",2,{a:1,b:3}]

3, Three methods of judging arrays and their differences

1. Object.prototype.toString.call()

Every Object that inherits an Object has a toString method. If the toString method is not overridden, it will return [Object type], where type is the type of the Object. However, when other types directly use the toString method except for objects of type Object, they will directly return a string with all contents. Therefore, we need to use the call or apply method to change the execution context of the toString method.

const an = ['Hello','An'];
an.toString(); // "Hello,An"
Object.prototype.toString.call(an); // "[object Array]"

This method can judge all basic data types, even null and undefined.

Object.prototype.toString.call('An') // "[object String]"
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call(Symbol(1)) // "[object Symbol]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(function(){}) // "[object Function]"
Object.prototype.toString.call({name: 'An'}) // "[object Object]"

Object.prototype.toString.call() is often used to judge the built-in objects in the browser.

More implementations visible Talk about object prototype. toString

2. instanceof

The internal mechanism of instanceof , is to judge whether the , prototype of the type can be found in the prototype chain of the object.

Use {instanceof} to judge whether an object is an Array. Instanceof} will judge whether the prototype of the corresponding {Array} will be found on the prototype chain of the object. If found, it will return} true, otherwise it will return} false.

[]  instanceof Array; // true

However, instanceof can only be used to judge the object type, not the original type. And all object types instanceof Object are true.

[]  instanceof Object; // true

Supplement: implement an instanceof

// The instanceof operator is used to determine whether the prototype attribute of the constructor appears anywhere in the prototype chain of the object.
// realization:

function myInstanceof(left, right) {
  let proto = Object.getPrototypeOf(left), // Gets the prototype of the object
    prototype = right.prototype; // Gets the prototype object of the constructor

  // Judge whether the prototype object of the constructor is on the prototype chain of the object
  while (true) {
    if (!proto) return false;
    if (proto === prototype) return true;

    proto = Object.getPrototypeOf(proto);
  }
}

3,Array.isArray()

  • Function: used to judge whether the object is an array

  • Array.isArray() and {object prototype. toString. call()

    Array.isArray() is a newly added method in ES5. When there is no {array Isarray(), you can use object prototype. toString. Call() implementation.

    if (!Array.isArray) {
      Array.isArray = function(arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
      };
    }