preface

Recently in writing interview programming questions, often use array, often want to steal a lazy, with the method it provides, but the array method is not skilled, resulting in writing a lot of garbage code, a lot of places slightly modified words must become simple, efficient and elegant 👊

So ✍ this article takes a look at the features of JavaScript arrays, as the title suggests

Other articles:

  • The 9 basic operations of the “Algorithms and Data Structures” linked list 👍
  • [practical 👍] Recommend some great front-end sites
  • 54 JavaScript interview questions
  • [full of sincerity 👍]Chrome DevTools debugging tips, efficiency ➡️🚀🚀 ➡️
  • [suggestion 👍] Again 100 JS output questions sour cool continue (total 1.8W words + consolidate JS foundation)
  • [1.2w word 👍] To his girlfriend’s secret – how the browser works (on)
  • [1.1W word] To his girlfriend’s secret – how the browser works (rendering process) chapter

If you want to improve your coding skills, you can stay and read this article

After reading, you will get 👏

  • More clarity on common array manipulation methods
  • Handy way to write common arrays

If you like it, you can like it/follow it and support it. I hope you can get something out of this article

Click GitHub to download the code for this article

Start this article at 🉑


Array based

To write array methods by hand, you need to be able to use their apis

Create an array

			/ / literal
            let demo = [1.2.3]
            / / the constructor
            let demo1 = Array(),
                demo2 = Array(3),
                demo3 = Array(1.2.3),
                demo4 = new Array(1.2.3);
Copy the code

Method on the constructor

Array.of()

Create an instance of a new Array. See the difference with the Array constructor

Grammar:

Array.of(element0[, element1[, ...[, elementN]]])
Copy the code

Usage:

Array.of(7);       / / [7]
Array.of(1.2.3); / / [1, 2, 3]

Array(7);          // [,,,,,,]
Array(1.2.3);    / / [1, 2, 3]
Copy the code

The difference: array.of (7) creates an Array with a single element of 7, while Array(7) creates an empty Array of length 7.


Array.isArray()

Array.isarray () is used to determine whether the value passed is an Array.

Array.isArray([1.2.3]);  
// true
Array.isArray({foo: 123}); 
// false
Array.isArray("foobar");   
// false
Array.isArray(undefined);  
// false
Copy the code

Manual implementation

			// Array.isArray
            if(!Array.isArray){
                Array.isArray = obj= > Object.prototype.toString.call(obj) === '[object Array]'
            }
Copy the code

To determine the JS data type, check out my previous blog post about how typeof Instanceof works


Array.from()

The array.from () method creates a new, shallow-copy Array instance from an array-like or iterable.

Array.from(arrayLike[, mapFn[, thisArg]])
Copy the code
parameter
  • ArrayLike: Mandatory. You can pass 1, class arrays (Argumentg), 2, iterable objects (set,map).
  • MapFn: optional, equivalent to array. from(arrayLike). Map (mapFn, thisArg).
  • ThisArg: Optional, this object when the callback mapFn is executed. Very useful for decoupling. ThisArg defines the handle function, which is used to return the result after calling handle in mapFn.
usage

String

			// Array.from()
            const demo = Array.from('123')
            console.log(demo) //[ 'a', 'b', 'c' ]
Copy the code

new Set()

			const Array_demo = Array.from(new Set([1.2.3.4.1.2.3]))
            console.log(Array_demo)  / / [1, 2, 3, 4]
Copy the code

new Map()

const map = new Map([[1.2], [2.4], [4.8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]
Copy the code

An array of class

const fn = (function() {
    const demo = Array.from(arguments);
    console.log(demo); }) (1.2.3); // [1, 2, 3]
Copy the code

Array unmerges

			let fn = function () {
                console.log(arguments)
                const Arr_new = [].concat.apply([],arguments)
                return Array.from(new Set(Arr_new))
            }
            const   demo1 = [1.2.3.4],
                    demo2 = [4.5.6.2.2.2],
                    demo3 = [1.2.3.4.2.2.3.4];
            console.log(fn(demo1,demo2,demo3))
            / / [6]
Copy the code

Make full use of the third parameter thisArg

		const obj = {
            handle: x= > x * 4 
        }
        console.log(Array.from([11.22.33].function (x) {
            return this.handle(x)
        }, obj))
        / / [44, 88, 132]
Copy the code
Train of thought
  • Check whether arrayLike is empty
  • = mapFn(iValue, I); if not, arr[I] = iValue
  • ThisArg [I] = thisArg. Call (thisArg, iValue, I)

Start the array. from tour in array.js at line 1763 in V8

		/** * implement array. from * toInteger: returns an integer * toLength: Ensure len numbers are valid [0~ number.max_safe_integer] * number.max_safe_integer = math.pow (2,53) -1 * error if arrayLike is null * MapFn is non-empty and not a constructor throws an error * every time arrayLike is traversed, if mapFn is present, Call (thisArg, iValue, I) * */ arr[I] = thisArg (iValue, I) * */
        Array.myfrom = (function () {
            const toStr = Object.prototype.toString
            const isCallable = fn= > typeof fn === 'function' || toStr.call(fn) === '[object Function]'
            
            const toInteger = value= > {
                const v = Number(value)
                if(isNaN(v))    return 0
                // infinity or 0 returns directly
                if(v === 0 || !isFinite(v)) return v
                return (v > 0 ? 1 : - 1) * Math.floor(Math.abs(v))
            }
            // Maximum range number.max_safe_INTEGER
            const maxSafeInteger = Number.MAX_SAFE_INTEGER
            
            const toLength = value= > {
                const len = toInteger(value)
                return Math.min(maxSafeInteger, Math.max(0, len))
            }
            return function myfrom (arrayLike/*, mapFn, thisArg*/) {
                const that = this
                if(arrayLike === null) throw new TypeError("Array.from requires an array-like object - not null or undefined")
                
                const items = Object(arrayLike)
                let thisArg = ' '
                // if mapFn is undefined, it is better not to use undefined directly because undefined is not a reserved word.
                // If undefined is a value, use void 0 or void undefined
                const mapFn = arguments.length > 1 ? arguments[1] : void 0
                if( typeofmapFn ! = ='undefined') {
                    // Determine if the second argument is a constructor
                    if( !isCallable(mapFn) ) throw new TypeError("Array.from when provided mapFn must be a function")
                    if( arguments.length > 2) thisArg = arguments[2]}const len = toLength(items.length)
                const arr = isCallable(that) ? Object(new that(len)) : new Array(len)

                let i = 0,
                    iValue;
                while ( i < len) {
                    iValue = items[i]
                    if(mapFn) arr[i] = typeof thisArg === 'undefined' ? mapFn(iValue,i) : mapFn.call(thisArg, iValue, i)
                    else 
                        arr[i] = iValue
                    i++
                }
                arr.length = len
                return arr
            }
        })()
Copy the code

👍 has to say that the array. from() implementation, in fact, harvest a lot of things.


Common methods

For the sake of simple memory and easy search, the main methods are divided into three categories: array traversable methods, which will modify the original array methods and return new array methods.

Traversal methods

There are 12 methods that iterate over an array without changing the original array:

ES5: forEach, every, some, filter, map, reduce, reduceRight, ES6: find, findIndex, keys, values, and entriesCopy the code

forEach()

Grammar:

    array.forEach(callback(currentValue, index, arr), thisArg)
Copy the code

Parameters:

Callback: a function executed for each element in an array that takes one to three arguments the current element being processed in the currentValue array index (optional) The index of the current element being processed in the array ARr (optional)forThisArg The array the Each() method is operating on. ThisArg Is an optional argument when executing the callback function, used as the this valueCopy the code

Talk about thisArg usage

function Counter() {
  this.sum = 0;
  this.count = 0;
}
Counter.prototype.add = function(array) {
  array.forEach(function(entry) {
    this.sum += entry;
    ++this.count;
  }, this);
  // ^---- Note
};

const obj = new Counter();
obj.add([2.5.9]);
obj.count;
// 3 === (1 + 1 + 1)
obj.sum;
// 16 === (2 + 5 + 9)
Copy the code

Obviously, passing this in line 9 determines the problem to which this points in the forEach callback.

At line 14, obj calls add, so this refers to obj, which in forEach refers to obj.

** Note: ** If you pass a function argument using an arrow function expression, thisArg argument is ignored because the arrow function is lexically bound to the this value

Look at line 1258 of array.js in source v8 to begin the forEach tour

Let’s try to imitate writing one:

		/** * array.prototype. forEach(callback, thisArg); /** * array.prototype. forEach(callback, thisArg
        Array.prototype.myforEach = function (callback, thisArg) {
            if( this= =null ) throw new TypeError("this is null or not defined")
            let newArr = Object(this)
            let len = newArr.length >>> 0
            if( typeofcallback ! = ='function' ) throw new TypeError(callback + ' is not a function');
            let thatArg = arguments.length >= 2 ? arguments[1] : void 0
            let k = 0

            while( k < len ) {
                
                if(k in newArr){ 
                    callback.call(thatArg, newArr[k], k, newArr);
                }
                k++
            }
            return void 0
        }
Copy the code

From a code point of view, you need to pay attention to:

  • There is no way to exit the loop. You call the callback every time and return can only exit the callback
  • This method returns undefined, even if you return a value
  • ThisArg changes this in the callback function, as can be seen from the source code, and if the callback is an arrow function, we know that the arrow function cannot change this, so thisArg will be ignored

every()

Definition:

Tests whether all elements in an array pass the test of a specified function. It returns a Boolean value.

Grammar:

    array.every(function(currentValue, index, arr), thisArg)
Copy the code

Parameters:

Callback: a function executed for each element in the array, This function takes one to three arguments: currentValue the current element being processed in the array index (optional) The index of the current element being processed in the array arr (optional) The array that every() is operating on. ThisArg Optional argument, used as this value when the callback function is executedCopy the code

Usage:

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12.5.8.130.44].every(isBigEnough);   // false
[12.54.18.130.44].every(isBigEnough); // true
Copy the code

Look at line 1322 of array.js in source v8 to start every

		/** * Array.prototype.every(callback, thisArg) **/
        Array.prototype.myevery = function (callback, thisArg) {
            if( this= =null ) throw new TypeError("this is null or not defined")
            let newArr = Object(this)
            let len = newArr.length >>> 0
            if( typeofcallback ! = ='function' ) throw new TypeError(callback + ' is not a function');
            let thatArg = arguments.length >= 2 ? arguments[1] : void 0
            let k = 0

            while( k < len ) {
                
                if(k in newArr){ 
                    let testResult = callback.call(thatArg, newArr[k], k, newArr);
                    if( !testResult ) return false
                }
                k++
            }
            return true
        }
Copy the code

From a code point of view, you need to pay attention to:

  • In the case of an empty array, return true as long as the first argument is a callback
  • Return true each time, true at last, false otherwise
  • If thisArg parameter, thencallbackWhen calledthisValue, which is a global object in non-strict mode, passed in strict modeundefined, as shown in thethisEntries.
  • Every does not change the array
  • everyThe range of elements traversed is called the first timecallbackIt was decided before. In the calleveryElements added later to the array will not becallbackAccess to. If existing elements in the array are changed, they are passed incallbackThe value iseveryAccess their value at that moment. Elements that are deleted or that have never been assigned a value will not be accessed.

some

Definition:

Tests that at least one element in the array passes the provided function test. It returns a Boolean value

Grammar:

    array.some(function(currentValue, index, arr), thisArg)
Copy the code

Parameters:

Callback: a function executed for each element in the array, The function takes one to three arguments currentValue array the current element being processed index (optional) array the index of the current element being processed arr (optional) The array some() method is manipulating thisArg Optional argument, used as this value when the callback function is executedCopy the code

Usage:

function isBiggerThan10(element, index, array) {
  return element > 10;
}
[2.5.8.1.4].some(isBiggerThan10);  // false
[12.5.8.1.4].some(isBiggerThan10); // true

// This example mimics the includes() method. If the element exists in an array, the callback returns true:
var fruits = ['apple'.'banana'.'mango'.'guava'];

function checkAvailability(arr, val) {
  return arr.some(function(arrVal) {
    return val === arrVal;
  });
}

checkAvailability(fruits, 'kela');   // false
checkAvailability(fruits, 'banana'); // true
Copy the code

Look at line 1298 of array.js in source v8 to start some

		Array.prototype.some(callback, thisArg) **/
        Array.prototype.mysome = function (callback, thisArg) {
            if (this= =null) throw new TypeError("this is null or not defined")
            let newArr = Object(this)
            let len = newArr.length >>> 0
            if (typeofcallback ! = ='function') throw new TypeError(callback + ' is not a function');
            let thatArg = arguments.length >= 2 ? arguments[1] : void 0

            for (let i = 0; i < len; i++) {
                if (i in newArr && callback.call(thatArg, newArr[i], i, newArr))
                    return true
            }
            return false
        }
Copy the code

From a code point of view, you need to pay attention to:

  • Some doesn’t change the array
  • If you test with an empty array, in any case it returnsfalse
  • If you call a function that does not return a value, it will always return undefined, and then some will return the same valuefalse
  • Pass thisArg, the value of this in the callback function, depending on the rule this refers to.

filter

Definition:

Creates a new array that contains all the elements of the tests implemented through the provided function.

Grammar:

let newArray = array.filter(function(currentValue, index, arr), thisArg)
Copy the code

Parameters:

Callback: a function executed for each element in the array, This function takes one to three arguments currentValue array the current element being processed index (optional) array the index of the current element being processed arr (optional) The array that the filter() method is manipulating thisArg Optional argument, used as this value when the callback function is executedCopy the code

Usage:

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12.5.8.130.44].filter(isBigEnough);
// filtered is [12, 130, 44] 

var fruits = ['apple'.'banana'.'grapes'.'mango'.'orange'];

/** * Array filters items based on search criteria (query) */
function filterItems(query) {
  return fruits.filter(function(el) {
      return el.toLowerCase().indexOf(query.toLowerCase()) > - 1; })}console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']
Copy the code

Look at line 1245 of array.js in source v8 to start the filter journey

/** * Creates a new array containing all the elements of the tests implemented by the provided function. * Array.prototype.filter(callback, thisArg) * */
        Array.prototype.myfilter = function (callback, thisArg) {
            if (this= =null) throw new TypeError("this is null or not defined")
            let newArr = Object(this)
            let len = newArr.length >>> 0
            if (typeofcallback ! = ='function') throw new TypeError(callback + ' is not a function');
            let thatArg = arguments.length >= 2 ? arguments[1] : void 0,
                resultArr = new Array(len),
                count = 0

            for (let i = 0; i < len; i++) {
                if (i in newArr) {
                    if (typeof thatArg === 'undefined' && callback(newArr[i], i, newArr)) 
                        resultArr[count++] = newArr[i]
                    if (typeofthatArg ! = ='undefined' && callback.call(thatArg, newArr[i], i, newArr)) 
                        resultArr[count++] = newArr[i]
                }
            }
            resultArr.length = count
            return resultArr
        }
Copy the code

From a code point of view, you need to pay attention to:

  • A custom callback function must have a Boolean return value. If it does not return undefined by default, go to Boolean to false
  • The original array is not modified, but a new array is returned containing all the test elements implemented by the provided function
  • Returns an empty array if no elements pass
  • filterDoes not change the original array, it returns the filtered new array
  • filterThe range of elements traversed is called the first timecallbackIt was decided before. In the callfilterElements that are later added to the array are notfilterTo traverse. If existing elements are changed, they are passed incallbackThe value isfilterGo through their values at that moment. Elements that are deleted or never assigned are not traversed.
  • If it isfilterTo provide athisArgParameter, then it will be taken ascallbackWhen calledthisValue. Otherwise,callbackthisThe value will be a global object in non-strict mode and will be a global object in strict modeundefined.callbackWhat the delta function eventually observesthisValues are based on the usualFunction to see the rule of “this”Sure.
  • Pay special attention to the arrow function where this points to

map

Definition:

Creates a new array with the result that each element in the array is the value returned by calling the supplied callback once.

Grammar:

let newArray = array.map(function(currentValue, index, arr), thisArg)
Copy the code

Parameters:

Callback: a function executed for each element in the array, This function takes one to three arguments currentValue array the current element being processed index (optional) array the index of the current element being processed arr (optional) The array that the map() method is manipulating thisArg Optional argument, used as this value when the callback function is executedCopy the code

Usage:

// The square root of each element in the array
var numbers = [1.4.9];
var roots = numbers.map(Math.sqrt);
// Roots is [1, 2, 3], numbers is still [1, 4, 9]

var numbers = [1.4.9];
var doubles = numbers.map(function(num) {
  return num * 2;
});

// Doubles values are: [2, 8, 18]
// The numbers array is not modified: [1, 4, 9]

// Show how to use the map method on a String to get an array of ASCII characters for each character in the String:
var map = Array.prototype.map
var a = map.call("Hello World".function(x) { 
  return x.charCodeAt(0); 
})
// A is [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
Copy the code

Look at line 1333 of array.js in source v8 to start the map tour

Array.prototype.map(callback, thisArg) ** /
        Array.prototype.mymap = function (callback, thisArg) {
            if (this= =null) throw new TypeError("this is null or not defined")
            let newArr = Object(this)
            let len = newArr.length >>> 0
            if (typeofcallback ! = ='function') throw new TypeError(callback + ' is not a function');
            let thatArg = arguments.length >= 2 ? arguments[1] : void 0,
                resultArr = new Array(len),
                mappedValue

            for (let i = 0; i < len; i++) {
                if (i in newArr) {
                    // There may be some confusion
                    mappedValue = callback.call(thatArg, newArr[i], i, newArr)
                    resultArr[i] = mappedValue
                }
            }
            return resultArr
        }
Copy the code

What’s confusing about this is line 17, why can I just write this, so I don’t have to worry about the case where thisArg is void 0, I was thinking about the case, but think about it later, even if it’s undefined, your map is calling a callback, and the callback’s this, in non-strict mode, Is the window,

		var numbers = [1.4.9];
        var doubles = numbers.map(function (num) {
            console.log(this)    // window
            return num * 2;
        }, void 0);
Copy the code

👆 run the code on the console and you will see that when passed thisArg, undefined will still result in Window, which is of course undefined in strict mode, which is left for the reader to think about

From a code point of view, you need to pay attention to:

  • mapDo not modify the original array itself that calls it (of course you cancallbackChange the original array on execution)
  • When the callback function does not return a value, each value of the last new array is undefined
  • thisThe final value of phi is relative to phicallbackThe observability of the function is based onthisThe rule, this, refers to the problem
  • becausemapGenerates a new array when you do not intend to use the returned arraymapIt’s against design. PleaseforEachorfor-ofAlternative.
  • mapThe method handles the range of array elements incallbackMethod is determined before the first call. callmapArray elements appended after the method are not appendedcallbackAccess. If the existing array element changes, thecallbackThe value ismapThe value when the element is accessed.

reduce

Definition:

Execute a Reducer function (in ascending order) that you provide on each element in the array and summarize its results into a single return value.

Grammar:

let result = array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
Copy the code

Parameters:

Callback: A function executed for each element in the array that receives one to four parameter AccumulatorsThe current value currentValue
CurrentIndex indicates the currentIndex
Array an arrayInitialValue Is the value of the first argument when the callback function is first called. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error.Copy the code

Usage:

Simple use cases, more advanced use of reduce, and a reference link at 👇

const arr = [3.5.1.4.2];
const a = arr.reduce((t, v) = > t + v);
/ / is equivalent to
const b = arr.reduce((t, v) = > t + v, 0);
Copy the code

See GIF GIF how to explain 👇

This is probably the simplest way to use it, so let’s think a little bit more about 😼

Const double => x + x; // const double => x + x; const triple = x => 3 * x; const quadruple = x => 4 * x; // Function composition enabling pipe functionality const pipe = (... functions) => input => functions.reduce( (acc, fn) => fn(acc), input ); // Composedfunctions formultiplication of specific values const multiply6 = pipe(double, triple); const multiply9 = pipe(triple, triple); const multiply16 = pipe(quadruple, quadruple); const multiply24 = pipe(double, triple, quadruple); // Usage multiply6(6); // 36 multiply9(9); // 81 multiply16(16); // 256 multiply24(10); / / 240Copy the code

Sometimes, using Reduce well really makes development efficient ✊

See array.js** line 1505 in source v8 to start the Reduce journey

/** * Execute a reducer function (ascending) provided by you on each element in the Array and summarize its results into a single return value * array.prototype. reduce(callback, initialValue) ** /
        Array.prototype.myreduce = function (callback /*, initialValue*/ ) {
            if (this= =null) throw new TypeError("this is null or not defined")
            let newArr = Object(this)
            let len = newArr.length >>> 0
            if (typeofcallback ! = ='function') throw new TypeError(callback + ' is not a function');
            let initialValue,
                k = 0

            if (arguments.length >= 2) {
                initialValue = arguments[1]}else {
                while(k < len && ! (kin newArr))
                    k++
                if (k >= len)
                    throw new TypeError('Reduce of empty array with no initial value')
                initialValue = newArr[k++]
            }

            for (let i = k; i < len; i++) {
                if (i in newArr) {
                    initialValue = callback(initialValue, newArr[i], i, newArr)
                }
            }
            return initialValue
        }
Copy the code

From a code point of view, you need to pay attention to:

  • The first time the callback is executed,accumulatorcurrentValueThe value of is available in two cases: if calledreduce()providesinitialValue.accumulatorValues forinitialValue.currentValueTake the first value in the array; If not providedinitialValue, thenaccumulatorTake the first value in the array,currentValueTake the second value in the array.
  • If not providedinitialValueReduce executes the callback method starting at index 1, skipping the first index. If you provideinitialValue, starting at index 0.
  • If the array is empty and not providedinitialValueThat will be thrownTypeError
  • What if the array has only one element (regardless of position) and is not suppliedinitialValueOr there is an offerinitialValueBut if the array is empty, the unique value will be returned andcallbackWill not be executed.

Reduce is too powerful. If you are interested, you can have a good look at ✊

Of course, this parsing of the code gives you a better understanding of Reduce


reduceRight

Stack from right to left, like reduce, and the source code implementation naturally has ✍

Definition:

Accept a function as an accumulator and each value of the array (from right to left) is a single value. To summarize the result into a single return value.

Grammar:

let result = array.reduceRight(callback(accumulator, currentValue, currentIndex, array), initialValue)
Copy the code

Parameters:

Callback: A function executed for each element in the array that receives between one and four parameters accumulator that was returned by the callback function the last time it was called.The current value currentValue
CurrentIndex indicates the currentIndex
Array an arrayInitialValue The value of the accumulator when the callback function is first called. If the initial value is not provided, the last element in the array is used and skipped.Copy the code

Usage:

Here is an example of the difference with reduce 👏

var a = ['1'.'2'.'3'.'4'.'5']; 
var left  = a.reduce(function(prev, cur)      { return prev + cur; }); 
var right = a.reduceRight(function(prev, cur) { return prev + cur; }); 

console.log(left);  / / "12345"
console.log(right); / / "54321"
Copy the code

See array.js** line 1505 in source v8 to start the reduceRight journey

To do this, take a pointer like index and simulate the last bit of the array from back to front 😹 just note the boundary values

find findIndex

This method was added to the ECMAScript 6 specification and may not exist in some implementations.

Definition:

**find:** Returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined.

FindIndex: The index of the first element in the array provided by the test function. Otherwise, -1 is returned.

Grammar:

let ele = array.find(function(elemnet, index, arr), thisArg)
let eleIndex = array.findIndex(function(elemnet, index, arr), thisArg)
Copy the code

Parameters:

They have similar syntax

Callback: a function executed for each element in the array, This function takes one to three arguments: elemnet The current element being processed in the array index (optional) The index of the current element being processed in the array arr (optional) The array being operated on by the find method thisArg This optional argument, when the callback function is executed, is used as the this valueCopy the code

The find usage:

// Find the primes in the array
function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false; }}return element >1; } console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found console.log([4, 5, 8, 12].find(isPrime)); / / 5Copy the code

FindIndex usage:

// If the index of the first prime element does not exist, return -1
function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false; }}return element >1; } console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found console.log([4, 6, 7, 12].findIndex(isPrime)); / / 2Copy the code

Look at line 1633 of array.js** in source v8 to begin the find journey

		/** * returns the value of the first element in the array that satisfies the provided test function. Array.prototype.find(callback, thisArg) * */
        Array.prototype.myfind = function (callback /*, thisArg */ ) {
            if (this= =null) throw new TypeError("this is null or not defined")
            let newArr = Object(this)
            let len = newArr.length >>> 0
            if (typeofcallback ! = ='function') throw new TypeError(callback + ' is not a function');

            let thatArg = arguments.length >= 2 ? arguments[1] : void 0

            for (let i = 0; i < len; i++) {
                if (i in newArr && callback.call(thatArg, newArr[i], i, newArr))
                    return newArr[i]
            }
            return void 0
        }
Copy the code

The findIndex function works exactly the same way, returning the index ❗

From a code point of view, you need to pay attention to:

  • The find method does not change the original array
  • On the first callcallbackFunction determines the index range of the element, so infindNew elements added to the array after the method starts execution will not becallbackFunction to.
  • If one of the arrays has not beencallbackThe value of the element accessed by the function iscallbackThe delta function changes, so whencallbackWhen the function accesses it, its value will be the current value accessed based on its index in the array. The deleted element is still accessed, but its return value is undefined.
  • I’ve read a lot about find, and I personally don’t think it’s specifiedthisArgThe callback function this does not always refer to undefined.This conforms to the this pointing rule.

keys & values & entries

Definition:

The keys() method returns an Array Iterator containing each key in the Array.

The values() method returns a new Array Iterator containing the value of each index of the Array

The Entries () method returns a new Array Iterator containing the key/value pairs for each index in the Array.

Grammar:

arr.entries()
Copy the code

Usage:

Let me give you an example of one of them

const array1 = ['a'.'b'.'c'];
const iterator1 = array1.entries();
const iterator2 = array1.values();
const iterator3 = array1.keys();
console.log(iterator1);
/*Array Iterator {} __proto__:Array Iterator next:ƒ next() Symbol(symbol.tostringtag):"Array Iterator" __proto__:Object * /	
Copy the code

iterator.next()

var arr = ["a"."b"."c"]; 
var iterator = arr.entries();
console.log(iterator.next());

/*{value: Array(2), done: false} done:false value:(2) [0, "a"] __proto__: Object */
Iterator.next () returns an object. For arrays with elements,
// next{value: Array(2), done: false};
// next-done indicates whether the iterator is complete: update at each iteration and always false,
Done is true until the iterator ends.
// next. Value is an array of ["key","value"] elements in the returned iterator.
Copy the code

useThe for… ofcycle

var arr = ["a"."b"."c"];
var iterator = arr.entries();
// undefined

for (let e of iterator) {
    console.log(e);
}

// [0, "a"] 
// [1, "b"] 
// [2, "c"]
Copy the code

A lot of content, I hope you can carefully look at 🉑


Change the original array method

splice

Definition:

Modify an array by deleting or replacing existing elements or adding new ones in place, and return the modified contents as an array. Note that this method alters the original array

Grammar:

array.splice(start,deleteCount,item1,..... ,itemX)Copy the code

Parameters:

Start: Specifies the starting position of the modification (counting from 0)1. If the length of the array is exceeded, add the contents from the end of the array
2. If it is negative, it represents the number of bits from the end of the array (counting from -1, which means that -n is the NTH element penultimate and equivalent to array.length-n)
3. If the absolute value of a negative number is greater than the length of the array, the starting position is bit 0DeleteCount (Optional) : Integer representing the number of array elements to be removed1. If deleteCount is greater than the number of elements after start, all elements after start are deleted (including the start bit).
2. If deleteCount is omitted, or its value is greater than or equal to array. length-start, then all elements in the array after start are deleted.
3. If deleteCount is 0 or negative, the element is not removed. In this case, at least one new element should be added.item1, item2, ... (Optional) The element to be added to the array, starting at the start position. If not specified, splice() will delete only array elements.Copy the code

Usage:

// Delete 0 elements from bit 2 and insert "drum"
var myFish = ["angel"."clown"."mandarin"."sturgeon"];
var removed = myFish.splice(2.0."drum");

// myFish: ["angel", "Clown ", "drum", "mandarin"," Sturgeon "]
// Deleted element: [], no element is deleted
// Remove 0 elements from bit 2, insert "drum" and "guitar"
var removed2 = myFish.splice(2.0.'drum'.'guitar');
// myFish: [" Angel ", "Clown ", "drum", "guitar", "mandarin"," Sturgeon "]
// Deleted element: [], no element is deleted
Copy the code

Delete 1 element starting at bit 2 and insert “trumpet”

var myFish = ['angel'.'clown'.'drum'.'sturgeon'];
var removed = myFish.splice(2.1."trumpet");

// 运算后的 myFish: ["angel", "clown", "trumpet", "sturgeon"]
// Deleted element: ["drum"]
Copy the code

Delete 2 elements from bit 0 and insert “parrot”, “anemone”, and “blue”

var myFish = ['angel'.'clown'.'trumpet'.'sturgeon'];
var removed = myFish.splice(0.2.'parrot'.'anemone'.'blue');

// myFish after calculation: [" Parrot ", "Anemone "," Blue ", "Trumpet "," Sturgeon "]
// Removed element: ["angel", "Clown "]
Copy the code

Deletes 1 element from the second-to-last position

var myFish = ['angel'.'clown'.'mandarin'.'sturgeon'];
var removed = myFish.splice(2 -.1);

// myFish: ["angel", "Clown "," Sturgeon "]
// Deleted element: ["mandarin"]
Copy the code

Remove all elements starting with bit 2

var myFish = ['angel'.'clown'.'mandarin'.'sturgeon'];
var removed = myFish.splice(2);

// myFish: ["angel", "Clown "]
// Deleted element: ["mandarin", "sturgeon"]
Copy the code

See array.js** line 876 in source v8 to start the splice journey

I think this is a simple simulation, but the only thing that bothers me is the boundary value


sort

Definition:

Sort the elements of the array and return the array. Note that this method changes the array

Grammar:

arr.sort([compareFunction])
Copy the code

Parameters:

CompareFunction optional1. Used to specify functions that are sorted in a certain order. If omitted, the element is sorted by the Unicode loci of each character in the converted string.2. Specifies compareFunction,3. If compareFunction(a, b) is less than 0, then A is placed before B;4. If compareFunction(a, b) is equal to 0, the relative positions of a and B remain the same.5. If compareFunction(a, b) is greater than 0, b will be placed before A.Copy the code

Usage:

var numbers = [4.2.5.1.3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// Can also be written as:
var numbers = [4.2.5.1.3]; 
numbers.sort((a, b) = > a - b); 
console.log(numbers);

// [1, 2, 3, 4, 5]
Copy the code

Sort non-ASCII characters

// When sorting non-ASCII characters such as e, e, e, a, a, etc.
// Some strings in non-English languages require string.localecompare. This function sorts functions into the correct order.
var items = ['réservé'.'premier'.'cliché'.'communiqué'.'café'.'adieu'];
items.sort(function (a, b) {
  return a.localeCompare(b);
});

/ / the items is [' adieu ', 'cafe', 'cliche', 'communique', 'premier', 'reserve']
Copy the code

Sorting is a knowledge, which has a lot of content, such as the event complexity of an algorithm, space complexity, to be updated later.


pop

Definition:

Removes the last element from the array and returns the value of that element. This method changes the length of the array.

Grammar:

arr.pop()
// The element to be removed from the array (undefined if the array is empty).
Copy the code

Description:

1. The pop method removes and returns the last element from an array.2. The POP method determines the position of the last element based on the length attribute.3. If the length attribute is not included or cannot be converted to a value, length is set to 0 and undefined is returned.4. If you call pop() on an empty array, it returns undefined.Copy the code

Usage:

let myFish = ["angel"."clown"."mandarin"."surgeon"];

let popped = myFish.pop();

console.log(myFish); 
// ["angel", "clown", "mandarin"]

console.log(popped); 
// surgeon
Copy the code

🚀 🚀 🚀 knocked over


shift

Definition:

Removes the first element from the array and returns the value of that element. This method changes the length of the array.

Grammar:

arr.shift()
// The element removed from the array; Returns undefined if the array is empty.
Copy the code

Description:

1. The shift method removes the element whose index is 0 (that is, the first element) and returns the removed element, with the index value of the other elements reduced by 12. If the length attribute has a value of 0 (length 0), undefined is returned.3. The Shift method is not limited to arrays: it can be applied to array-like objects through call or apply4. It may not make sense to call this method for objects that do not have a length attribute, the last in a series of consecutive numeric attributes starting at 0.Copy the code

Usage:

let myFish = ['angel'.'clown'.'mandarin'.'surgeon'];

console.log('Before calling shift:' + myFish);
/ / "call before the shift: angel, clown, mandarin, surgeon"

var shifted = myFish.shift(); 

console.log('After calling shift:' + myFish); 
// "After calling Shift: Clown, Mandarin,surgeon"

console.log('Deleted element:' + shifted); 
// "Deleted element: angel"
Copy the code

🚀🚀🚀 should be no difficulty


unshift

Definition:

Adds one or more elements to the beginning of an array and returns the new length of the array

Grammar:

arr.unshift(element1, ... , elementN)// element The element or elements to be added to the beginning of an array.
Copy the code

Description:

1. The unshift method inserts the given argument at the beginning of the array-like object on which it is called.2. Unshift is purposely designed to be universal; This method can be applied to an array-like object using either the Call or apply methods3. However, it might not make sense to call this method for objects that do not have the length attribute, which represents the last of a series of consecutive numeric attributes starting at 0.4. Note that if multiple arguments are passed in, they are inserted as blocks at the beginning of the object in the same order as when they were passed in as arguments5. , calling unshift once passing multiple arguments, and calling unshift multiple times passing one argument (for example, loop calls) will get different results. Such as:Copy the code

Usage:

let arr = [4.5.6];
arr.unshift(1.2.3);
console.log(arr); // [1, 2, 3, 4, 5, 6]

arr = [4.5.6]; // Reset the array
arr.unshift(1);
arr.unshift(2);
arr.unshift(3);
console.log(arr); // [3, 2, 1, 4, 5, 6]
Copy the code

Let’s do another example

arr.unshift(0); // result of the call is 3, which is the new array length
// arr is [0, 1, 2]

arr.unshift(2 -.- 1); // the new array length is 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([4 -.- 3]); // the new array length is 6
// arr is [[-4, -3], -2, -1, 0, 1, 2]

arr.unshift([7 -.- 6], [- 5]); // the new array length is 8
// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
Copy the code

🚀🚀🚀 should be no difficulty


push

Definition:

Adds one or more elements to the end of an array and returns the new length of the array

Grammar:

arr.push(element1, ... , elementN)// element The element or elements to be added to the end of an array.
// Put value back: When this method is called, the new length property value is returned.
Copy the code

Description:

1. Push method has universality. This method, when used with call() or apply(), can be applied to array-like objects.2. The push method uses the length attribute to decide where to start inserting a given value.3. If length cannot be converted to a numeric value, the index of the inserted element is 0, including if length does not exist. Length will be created when it does not exist.Copy the code

Usage:

Adds elements to an array

var sports = ["soccer"."baseball"];
var total = sports.push("football"."swimming");

console.log(sports); 
// ["soccer", "baseball", "football", "swimming"]

console.log(total);  
/ / 4
Copy the code

Use objects like arrays

var obj = {
    length: 0.addElem: function addElem (elem) {
        // obj.length is automatically incremented 
        // every time an element is added.
        [].push.call(this, elem); }};// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length);
/ / - > 2
// Note that although obj is not an array, the push method successfully increases the length property of obj, just as we would with an actual array.
Copy the code

Go ahead, there should be no difficulties need to be 🚀🚀🚀


reverse

Definition:

Reverses the position of the elements in an array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the original array.

Grammar:

arr.reverse()
// Put back the value: reversed array
Copy the code

Description:

1. The Reverse method reverses the position of the elements in the array, changes the array, and returns a reference to the array.2. The Reverse method is intentionally classified; This method can be called or applied to an array-like object.3. An object that does not contain an attribute that reflects the last length of a series of contiguous, zero-based numeric attributes may not behave in any meaningful way.Copy the code

Usage:

Inverts the elements of an array

const a = [1.2.3];

console.log(a); / / [1, 2, 3]

a.reverse(); 

console.log(a); / / [3, 2, 1)
Copy the code

Inverts the elements in the class array

onst a = {0: 1, 1: 2, 2: 3, length: 3};

console.log(a); // {0: 1, 1: 2, 2: 3, length: 3}

Array.prototype.reverse.call(a); //same syntax for using apply()

console.log(a); // {0: 3, 1: 2, 2: 1, length: 3}
Copy the code

copyWithin

Definition:

Shallowly copies part of an array to another location in the same array and returns it without changing the length of the original array.

Grammar:

    array.copyWithin(target, start = 0, end = this.length)
// Put back the value: changed array.
Copy the code

Parameters:

target
1. 0 is the base index, and the sequence is copied to that position. If it is negative, target will count from the end.2. If target is greater than or equal to arr.length, no copy will occur. If target is after start, the copied sequence is modified to match arr.length. start1. 0 is the base index at which the copy element starts. If it is negative, start is evaluated from the end.2. If start is ignored, copyWithin will start copying from 0. end1. 0 is the index of the base and the end position of the start copy element. CopyWithin will be copied to that location, but not to the end element. If it is negative, end is evaluated from the end.2. If end is ignored, the copyWithin method is copied all the way to the end of the array (arr.length by default).Copy the code

Note:

1. The parameters target, start, and end must be integers.2. If start is negative, the specified index position is equal to length+start, where length is the length of the array. The same is true of end.3. CopyWithin is a mutable method that does not change the length of this, but changes the content of this itself, and creates new properties as needed.Copy the code

Usage:

const a = [1.2.3];
[1.2.3.4.5].copyWithin(2 -)
// [1, 2, 3, 1, 2]

[1.2.3.4.5].copyWithin(0.3)
// [4, 5, 3, 4, 5]

[1.2.3.4.5].copyWithin(0.3.4)
// [4, 2, 3, 4, 5]

[1.2.3.4.5].copyWithin(2 -.- 3.- 1)
// [1, 2, 3, 3, 4]

[].copyWithin.call({length: 5.3: 1}, 0.3);
// {0: 1, 3: 1, length: 5}
console.log(a); / / [1, 2, 3]

a.reverse(); 

console.log(a); / / [3, 2, 1)
Copy the code

I may not use this method to solve the problem, looking at my headache ❌


fill

Definition:

Fills all elements in an array from the start index to the end index with a fixed value. Does not include terminating indexes.

Grammar:

    arr.fill(value, start, end )
// Put back the value: the modified array.
Copy the code

Parameters:

value
1. The value used to populate an array element. Start (optional)1. Start index. Default value is 0. End (optional)1. Terminates the index. Default is this.length.Copy the code

Description:

1. If start is negative, the start index is automatically evaluated as length+start, where length is the value of the length attribute of this object2. The fill method is intentionally generic and does not require this to be an array object.3. The fill method is a mutable method that changes the this object on which it was called, and then returns it instead of returning a copy.4. When an object is passed to the fill method, the array is filled with a reference to the object.Copy the code

Usage:

[1.2.3].fill(4);               / / (4, 4, 4]
[1.2.3].fill(4.1);            / / [1, 4, 4]
[1.2.3].fill(4.1.2);         / / [1, 4, 3)
[1.2.3].fill(4.1.1);         / / [1, 2, 3]
[1.2.3].fill(4.3.3);         / / [1, 2, 3]
[1.2.3].fill(4.- 3.2 -);       / / [4, 2, 3]
[1.2.3].fill(4.NaN.NaN);     / / [1, 2, 3]
[1.2.3].fill(4.3.5);         / / [1, 2, 3]
Array(3).fill(4);                / / (4, 4, 4]
[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}
// Objects by reference.
var arr = Array(3).fill({}) / / / {}, {}, {};
// Note that if fill takes a reference type, it will result in a single reference type being executed
// 如 arr[0] === arr[1] 为true
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
Copy the code

Look at line 1700 of array.js in source v8 to begin the fill journey

if (!Array.prototype.fill) {
  Object.defineProperty(Array.prototype, 'fill', {
    value: function(value) {

      // Steps 1-2.
      if (this= =null) {
        throw new TypeError('this is null or not defined');
      }

      var O = Object(this);

      // Steps 3-5.
      var len = O.length >>> 0;

      // Steps 6-7.
      var start = arguments[1];
      var relativeStart = start >> 0;

      // Step 8.
      var k = relativeStart < 0 ?
        Math.max(len + relativeStart, 0) :
        Math.min(relativeStart, len);

      // Steps 9-10.
      var end = arguments[2];
      var relativeEnd = end === undefined ?
        len : end >> 0;

      // Step 11.
      var final = relativeEnd < 0 ?
        Math.max(len + relativeEnd, 0) :
        Math.min(relativeEnd, len);

      // Step 12.
      while (k < final) {
        O[k] = value;
        k++;
      }
      // Step 13.
      returnO; }}); }Copy the code

Code for four hours, MY code does not move ✍, look at others standard writing, let me go 😭


Do not change the original array method

slice

Definition:

Returns a new array object that is a shallow copy of the array determined by begin and end (begin, but not end). The original array will not be changed.

For deep copy, take a look at my interview on how to write a satisfactory deep copy (suitable for the beginning front-end)

Grammar:

arr.slice([begin[, end]])
Copy the code

Parameters:

Begin (Optional) 1. Extract the original array elements from the index starting from 0. Slice (-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) slice(-2) If begin is omitted, slice starts at index 0. 5. If begin is greater than the length of the original array, an empty array is returned. End (optional) 1. Slice (1,4) extracts all elements (indexes 1, 2, 3) from the second element through the fourth element in the array. If this parameter is negative, it indicates the penultimate element in the original array at the end of the extraction. 3. If end is omitted, slice extracts all the way to the end of the array. 4. If end is greater than the length of the array, Slice will also extract to the end of the array.Copy the code

Usage:

Returns a portion of an existing array

var fruits = ['Banana'.'Orange'.'Lemon'.'Apple'.'Mango'];
var citrus = fruits.slice(1.3);

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
Copy the code

When a reference type value exists in the array, the shallow copy is the reference type address

// Create a newCar from myCar using the slice method.
var myHonda = { color: 'red'.wheels: 4.engine: { cylinders: 4.size: 2.2}};var myCar = [myHonda, 2."cherry condition"."purchased 1997"];
var newCar = myCar.slice(0.2);
newCar[0].color = 'blue';
console.log(myHonda.color)  // bule
Copy the code

Class array objects are converted to arrays

function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1.2.3); / / [1, 2, 3]
// You can also simply use [].slice.call(arguments) instead
Copy the code

Look at line 762 of array.js in source v8 to begin slice’s journey

(function () {
  'use strict';
  var _slice = Array.prototype.slice;

  try {
    // Can't be used with DOM elements in IE < 9
    _slice.call(document.documentElement);
  } catch (e) { // Fails in IE < 9
    // This will work for genuine arrays, array-like objects, 
    // NamedNodeMap (attributes, entities, notations),
    // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
    // and will not fail on other DOM objects (as do DOM elements in IE < 9)
    Array.prototype.slice = function(begin, end) {
      // IE < 9 gets unhappy with an undefined end argument
      end = (typeofend ! = ='undefined')? end :this.length;

      // For native Array objects, we use the native slice function
      if (Object.prototype.toString.call(this) = = ='[object Array]') {return _slice.call(this, begin, end); 
      }
      // For array like object we handle it ourselves.
      var i, cloned = [],
        size, len = this.length;
      // Handle negative value for "begin"
      var start = begin || 0;
      start = (start >= 0)? start :Math.max(0, len + start);
      // Handle negative value for "end"
      var upTo = (typeof end == 'number')?Math.min(end, len) : len;
      if (end < 0) {
        upTo = len + end;
      }
      // Actual expected size of the slice
      size = upTo - start;
      if (size > 0) {
        cloned = new Array(size);
        if (this.charAt) {
          for (i = 0; i < size; i++) {
            cloned[i] = this.charAt(start + i); }}else {
          for (i = 0; i < size; i++) {
            cloned[i] = this[start + i]; }}}return cloned;
    };
  }
}());
Copy the code

I think this is a simulation process, and the only difficulty is the determination of boundary value, so I have found a code under the specification for your reference.

From a code point of view, you need to pay attention to:

  • For usage, see the parameters section 🈯
  • For the depth copy problem, if the element is an object reference (not an actual object),sliceWill copy the object reference into the new array. Both object references refer to the same object. If the referenced object changes, the element in the new and original array changes as well.
  • If you add a new element to either array, the other is unaffected.
  • Deep copy, check out this article on how to write a satisfactory deep copy (suitable for the beginning front-end)

join

Definition:

Concatenate all the elements of an array (or an array-like object) into a string and return the string. If the array has only one item, that item is returned without a delimiter.

Grammar:

arr.join(separator)
Copy the code

Parameters:

Separator (Optional) Specifies a string to separate each element of the array. Convert the delimiter to a string if necessary. If default, array elements are separated by commas (,). If separator is an empty string (""), there are no characters between all elements.Copy the code

Usage:

Concatenate array elements using four different delimiters

var a = ['Wind'.'Rain'.'Fire'];
var myVar1 = a.join();      // myVar1 changes to "Wind,Rain,Fire"
var myVar2 = a.join(', ');  // myVar2 changes to "Wind, Rain, Fire"
var myVar3 = a.join('+'); // myVar3 changes to "Wind + Rain + Fire"
var myVar4 = a.join(' ');    // myVar4 changes to "WindRainFire"
Copy the code

Join class array objects

function f(a, b, c) {
  var s = Array.prototype.join.call(arguments);
  console.log(s); // '1,a,true'
}
f(1.'a'.true);
Copy the code

See array.js at line 468 in source v8 to start the join tour

Separator each item of an array or array-like object, and finally concatenate the string with separator


toString

Definition:

Returns a string representing the specified array and its elements.

Grammar:

arr.toString()
Copy the code

When an array is used as a text value or as a string concatenation, its toString method is automatically called.

Usage:

const array1 = [1, 2, 'a'.'1a'];
console.log(array1.toString());
// expected output: "1, 2, a, 1 a"
Copy the code

concat

Definition:

Used to merge two or more arrays. This method does not change an existing array, but returns a new array.

Grammar:

var newArr =oldArray.concat(arrayX,arrayX,...... ,arrayX)Copy the code

Parameters:

Arrayx (optional) joins arrays and/or values into a new array. If the valueN argument argument is omitted, concat returns a shallow copy of the existing array it called.Copy the code

Usage:

The following code merges two arrays into a new array:

var alpha = ['a'.'b'.'c'];
var numeric = [1.2.3];

alpha.concat(numeric);
// result in ['a', 'b', 'c', 1, 2, 3]
Copy the code

Concatenate three arrays

var num1 = [1.2.3],
    num2 = [4.5.6],
    num3 = [7.8.9];
var nums = num1.concat(num2, num3);
console.log(nums); 
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

Concatenate values to arrays

var alpha = ['a'.'b'.'c'];

var alphaNumeric = alpha.concat(1[2.3]);

console.log(alphaNumeric); 
// results in ['a', 'b', 'c', 1, 2, 3]
Copy the code

Note:

  • concatThe method will not changethisOr any array supplied as an argument, but returns a shallow copy
  • concatCopy the object reference into the new array. Both the original and new arrays refer to the same object. That is, if the referenced object is modified, the change is visible to both the new array and the original array. This includes elements that are also array parameters of arrays.
  • The array/value remains unchanged at join time. In addition, any operation on the new array (only if the element is not an object reference) has no effect on the original array, and vice versa.

indexOf

Definition:

Returns the first index in the array where a given element can be found, or -1 if none exists.

Grammar:

      array.indexOf(searchElement,fromIndex)
Copy the code

Parameters:

SearchElement (Mandatory) fromIndex the element to be found1. The location to start the search. If the index value is greater than or equal to the length of the array, it means that it is not searched in the array, and returns -1.2. If the index value provided in the argument is a negative value, it is treated as an offset at the end of the array, with -1 indicating that the search starts from the last element3.  Note: If the index value provided in the argument is a negative value, the lookup order does not change, and the lookup order is still the array queried from front to back. If the offset index is still less than 0, the entire array will be queried. The default value is 0.4. It's strictly equal to === =Copy the code

Usage:

The indexOf method determines the position of multiple values in an array

var array = [2.5.9];
array.indexOf(2);     / / 0
array.indexOf(7);     // -1
array.indexOf(9.2);  / / 2
array.indexOf(2.- 1); // -1
array.indexOf(2.- 3); / / 0
Copy the code

Finds all locations where the specified element appears

var indices = [];
var array = ['a'.'b'.'a'.'c'.'a'.'d'];
var element = 'a';
var idx = array.indexOf(element);
while(idx ! =- 1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
/ / [0, 2, 4]
Copy the code

IndexOf () does not recognize NaN

		let a = ['now!'.2.4.24.NaN]
        console.log(a.indexOf('! ')); // -1 
        console.log(a.indexOf(NaN)); // -1 
        console.log(a.indexOf('now!')); / / 0
Copy the code

Look at line 1411 of array.js in source v8 to start the indexOf journey

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;
    // 1. Let O be the result of calling ToObject passing
    // the this value as the argument.
    if (this= =null) {
      throw new TypeError('"this" is null or not defined');
    }

    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get
    // internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return - 1;
    }
    // 5. If argument fromIndex was passed let n be
    // ToInteger(fromIndex); else let n be 0.
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }
    // 6. If n >= len, return -1.
    if (n >= len) {
      return - 1;
    }
    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    // If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    // 9. Repeat, while k < len
    while (k < len) {
      if (k in O && O[k] === searchElement) {
        return k;
      }
      k++;
    }
    return - 1;
  };
}
Copy the code

This is a standard code, you can refer to, I will not write, I have to go on a date, no time 🙏

lastIndexOf

Definition:

Returns the index of the last element in the array for the specified element (that is, a valid JavaScript value or variable), or -1 if none exists. Look forward from the back of the array, starting at fromIndex.

Grammar:

          arr.lastIndexOf(searchElement,fromIndex)
Copy the code

Parameters:

SearchElement (Mandatory) fromIndex the element to be found1. Start looking backwards from this location2. The default is the length of the array minus 1(arr.length-1), that is, the entire array is searched3.  If the value is greater than or equal to the length of the array, the entire array is searched. If it is negative, it is treated as an offset forward from the end of the array4. Even if the value is negative, the array will still be looked up backwards. If the value is negative and its absolute value is greater than the array length, the method returns -1, meaning that the array is not found.Copy the code

Usage:

The index of the last occurrence of the element in the array, if not found, returns -1.

var array = [2.5.9.2];
var index = array.lastIndexOf(2);
// index is 3
index = array.lastIndexOf(7);
// index is -1
index = array.lastIndexOf(2.3);
// index is 3
index = array.lastIndexOf(2.2);
// index is 0
index = array.lastIndexOf(2.2 -);
// index is 0
index = array.lastIndexOf(2.- 1);
// index is 3
Copy the code

See how an indexOf is implemented 🤳, out of time.


conclusion

Want to cry without tears 🤥, code a day + code to complete these JS array knowledge, found “1.2W word” 👍👍👍 many definitions refer to the official website, mainly for fear of misleading a lot of people like me belong to the basic front-end staff, so use the official website standard terminology.

The code is difficult to write, harvest a lot, need to exercise their code ability, can take a good practice.

If you like, you can like 👍👍👍/ follow, support, hope you can read this article to gain

reference

MDN_Array

JS array kit Kat trick

V8 source

JS traversal in detail

25 Advanced Uses of Array Reduce that you Need to know

The 9 basic operations of the “Algorithms and Data Structures” list