This is the 25th day of my participation in Gwen Challenge

preface

There are many new properties, methods, and features in ES6, and this series will re-learn ES6 through simulation implementations to help you better understand those new things.

Objective of this article: to understand the new additions to the ES6 array through simulation

Description: In this paper, the method is briefly introduced, and then complete the simulation

Simulate the implementation of array additions

A static method

Array.from()

introduce

Arguments: The first argument takes an array of classes or other data structure that deploys the Iterator interface. The second optional argument takes a function that acts like Map

Function: Converts the first argument received into a real array, and can be collated by the second argument

Return value: Returns a new array without changing the original object

Array._from()

Array._from = (likeArray, callback) = > {
    let res = [].slice.call(likeArray)
    return (typeof callback == 'function')? res.callback() : res }console.log(Array._from('asd'))// ["a", "s", "d"]
console.log(Array.from('asd'))// ["a", "s", "d"]
let divs = document.querySelectorAll('div')
console.log(Array._from(divs))//[div, div, div]
console.log(Array.from(divs))//[div, div, div]
Copy the code

Array.of()

introduce

Parameter: N parameters can be accepted

Function: Converts a set of parameters to an array

Return value: Returns the array

Array._of()

Array._of = (. args) = > args;
console.log(Array._of(1.2.3))/ / [1, 2, 3]
console.log(Array.of(1.2.3))/ / [1, 2, 3]
Copy the code

Instance methods

copyWithin()

introduce

Parameter: can receive three parameters, and the parameter is usually a value, if not a value will be converted to a value, if there is a negative number, indicates the last digit. The first argument replaces data from that location, the second argument reads data from that location (default: 0), and the third argument reads data to that location (default: array length)

Function: Copies data from a specified position in an array to a specified position, and then replaces the corresponding length of data from the specified position

Return value: Returns the current array, which changes the original array

_copyWithin()

Array.prototype._copyWithin = function (target, start = 0, end = this.length) {
    // 1
    if (target < 0) {
        target += this.length
    }
    if (start < 0) {
        start += this.length
    }
    if (end < 0) {
        end += this.length
    }
    // 2. Find the values to be copied and replace them one by one
    for (let index = start; index < end; index++) {
        // this[index]; // The value to be copied
        if (target < this.length) {
            console.log(this[target],this[index])
            this[target] = this[index];
            target++
        }
    }
    return this
}
console.log([1.2.3.4].copyWithin(2))/ / [1, 2, 1, 2]
console.log([1.2.3.4]._copyWithin(2))/ / [1, 2, 1, 2]
Copy the code

find()

introduce

Arguments: The first argument is a callback function and the second argument is this to point to

Returns the first eligible array member by iterating through the array members and executing a callback

Return value: Returns undefined if the first member whose return value is true after the callback is not found

_find()

Array.prototype._find = function (callback, self) {
    if (typeof callback === 'function') {
        if (this.length) {
            for (let i = 0; i < this.length; i++) {
                // Find each member in the incoming callback and return the value if true
                if (callback.call(self, this[i], i, this)) {
                    return this[i]
                }
            }
        }
    }
}
let a = [1.2.3]    
console.log(a._find(function (val, index, arr) { return val == 1 }));/ / 1
console.log(a.find(function (val, index, arr) { return val == 1 }));/ / 1
Copy the code

findIndex()

introduce

Arguments: The first argument is a callback function and the second argument is this to point to

The find method is used to find the index of the first array member that meets the criteria

Return value: Returns the index of the first eligible member

_findIndex()

Array.prototype._findIndex = function (callback, self) {
    if (typeof callback === 'function') {
        if (this.length) {
            for (let i = 0; i < this.length; i++) {
                // Find each member in the incoming callback and return the value if true
                if (callback.call(self, this[i], i, this)) {
                    return i
                }
            }
        }
    }
}
let a = [1.2.3]    
console.log(a._findIndex(function (val, index, arr) { return val == 1 }));/ / 0
console.log(a.findIndex(function (val, index, arr) { return val == 1 }));/ / 0
Copy the code

fill()

introduce

Parameters: three parameters can be received, indicating what to fill, the start position of the fill, the end position of the fill; The default values for the last two options are 0 and array length, respectively

Used to fill an array, to fill the specified location

Return value: Returns the populated array, which changes the original array

Mock implementation: _fill()

Array.prototype._fill = function (data, start = 0, end = this.length) {
    // Handle negative values
    if (start < 0) {
        start += this.length
    }
    if (end < 0) {
        end += this.length
    }
    / / fill
    for (let i = start; i < end; i++) {
        this[i] = data;
    }
    return this
}
console.log(new Array(5)._fill('a', -2))//[empty × 3, "a", "a"]
console.log(new Array(5).fill('a', -2))//[empty × 3, "a", "a"]
Copy the code

Entries (), keys(), values()

introduce

They’re about the same. They’re all together

Parameters: no

What it does: keys() is key name traversal, values() is key value traversal, and entries() is key value pair traversal

Return value: Both return a traverser object

Simulated implementation: _keys()

Array.prototype._keys = function (){ 
    let temp = []   
    for (let i = 0; i < this.length; i++) {
        temp.push(i)       
    }
    return temp[Symbol.iterator]()
}
let arr = ['a'.'b'.'c']
console.log(arr._keys(),arr.keys());
for (const iterator of arr._keys()) {
    console.log(iterator);
}
for (const iterator of arr.keys()) {
    console.log(iterator);
}
Copy the code

The results are as follows:

Simulated implementation: _values()

Array.prototype._values = function (){ 
    let temp = []   
    for (let i = 0; i < this.length; i++) {
        temp.push(this[i])       
    }
    return temp[Symbol.iterator]()
}
let arr = ['a'.'b'.'c']
for (const i of arr._values()) {
    console.log(i);
}
for (const i of arr.values()) {
    console.log(i);
}
Copy the code

Analog implementation: _entries()

Array.prototype._entries = function (){ 
    let temp = []   
    for (let i = 0; i < this.length; i++) {
        temp.push([i,this[i]])       
    }
    return temp[Symbol.iterator]()
}
Copy the code

includes()

introduce

Parameter: Receives a value to be judged

Function: Determines whether the given value is contained in an array

Return value: Returns true or false

Simulation implementation: _includes()

Array.prototype._includes = function (x) {
    for (let i = 0; i < this.length; i++) {
        if (Number.isNaN(x) && Number.isNaN(this[i])) {
            return true
        }
        if (x === this[i]) {
            return true}}return false
}
let arr = [1.2.3.4.NaN]
console.log(arr._includes(2))//true
console.log(arr._includes(NaN))//true
console.log(arr._includes(5))//false
Copy the code

flat()

introduce

Parameter: Receives an integer

Function: Used to flatten or flatten an array, the depth of flatten depends on the parameter passed. The default is 2, which flatten a two-dimensional array

Return value: Returns the flattened array without changing the original array

Analog implementation: _flat()

Array.prototype._flat = function (n = 1) {
    return this.reduce((acc, val) = > {
        return acc.concat(Array.isArray(val) && n > 0 ?
            val.flat(--n) : Array.isArray(val) ? [val] : val); }}, [])let arr = [1[2.3], ['a'.'b'['c'.'d']]]
console.log(arr._flat(3))//[1, 2, 3, "a", "b", "c", "d"]
Copy the code

END

So that’s a mock implementation of some of the new stuff on the array!

The real implementation may be different from what I wrote, but it doesn’t matter, as long as we are familiar with what these methods do, we have achieved the purpose of this study!

If you have any questions or suggestions, please leave a message. Thank you!