JavaScriptAll you need to know about arrays is

1.ES6New array method

Array.from(), array.of (), copyWithin(), find(), findIndex(), fill(), entries(), keys(), values(), includes().

2,ES5New array method

ForEach (), map(), filter(), some(), every(), indexOf(), lastIndexOf(), reduce(), reduceRight().

3, Which of these array methods can change the original array?

CopyWithin (), fill(), pop(), push(), reverse(), shift(), sort(), splice().

4,someeveryWhat’s the difference?

Some is some, every is every, and both return a Boolean value.

5. There are 100,000 items in the array. Which one will take the first element or the 100,000th element?

The time is basically the same, because there’s no array type in JS, and an array is actually an object, a key and a value.

6, How many methods do you have for array deduplication?

1. Multi-layer cycle traversal method

  • doubleforCycle;
  • Recursive loop.

2. Take advantage of syntax’s own key unrepeatability or API de-duplication

  • ES6 SetGo to the heavy;
  • Create an empty object to remove weight;
  • Single layer circulation +filter/includes/indexOf;
  • Single layer circulation +Map,Objectduplicate removal

7,forCirculation andforEachWhich performance is better?

forLoops perform better

  • forThe loop does not have any additional function call stack or context;
  • forEachNot ordinaryforThe syntax of the loop, as well as the many parameters and contexts that need to be taken into account during execution, can be slow.

Eight,sortIn what way is the sort sorted?

The default sort order is built when converting elements to strings and then comparing their UTF-16 code unit value sequences.

9. Convert multidimensional arrays to one-dimensional arrays

  • reduceThe recursive implementation
  • joinsplitimplementation
  • The recursive traversal
  • flatmethods
  • toStringsplitimplementation
  • Breadth first traversal/depth first traversal

10. How to implement breadth-first and depth-first traversal

JS depth first traversal and breadth first traversal

1. Depth-first traversal

  • Access to the verticesv;
  • In turn, fromvThe graph is traversed depth-first. Until the diagram is neutralvAll vertices with paths connected are accessed.
  • If there are still vertices that are not visited, the depth-first traversal is performed again from an unvisited vertex until all vertices are visited.
const depth = (node) = > {
    let stack = []
    let nodes = []
    if (node) {
        stack.push(node)
        while (stack.length) {
            // Take the last one at a time
            let item = stack.pop()
            let children = item.children || []
            nodes.push(item)
            // Determine the length of children
            for (let i = children.length - 1; i >= 0; i--) {
                stack.push(children[i])
            }
        }
    }
    return nodes
}
Copy the code

2. breadth-first traversal

  • Create a queue and put the start node in the queue;
  • If the queue is not empty, the first node is removed from the queue and detected whether it is the target node.
  • If the target node, the search ends and the result is returned.
  • If not, all its undetected byte points are queued.
  • If the queue is empty, there is no target node in the graph and the traversal ends.
const breadth = (node) = > {
    let nodes = []
    let stack = []
    if (node) {
        stack.push(node)
        while (stack.length) {
            // take the first one
            let item = stack.shift()
            let children = item.children || []
            nodes.push(item)
            for (let i = 0; i < children.length; i++) {
                stack.push(children[i])
            }
        }
    }
    return nodes
}
Copy the code

11. Implement onereduce

Array.prototype.myReduce = function (fn, init) {
    if(! init &&this.length === 0) { // If the array length is 0
        return this
    }
    let start = 1, pre = this[0]; // Start from the second array with subscript 1
    if(init ! = =undefined) { // If init field exists, start with the first one, subscript 0
        start = 0;
        pre = init;
    }
    for (let i = start; i < this.length; i++) { / / loop
        let current = this[i]
        pre = fn.call(this, pre, current, i, this) // Return the value of each reduce
    }
    return pre
}
Copy the code

12, implement a random array shuffling algorithm

function disOrder2 (arr) {
    for (let i = 0; i < arr.length; i++) { / / traverse
        const randomIndex = Math.floor(Math.random() * ary.length) // Generate a random number
        swap(arr, i, randomIndex)
    }
}
function swap(arr, i, _i) { / / exchange
    const tem = arr[i]
    arr[i] = arr[_i]
    arr[_i] = tem  
}
arr = [1.2.3.4.5.6.7.8]
disOrder(arr)
console.log(arr)
Copy the code

13. Separate a string of numbers by commas

1. Regular

num.replace(/(\d)(? =(\d{3})+(\.|$))/g."$1")
Copy the code

2. Traversal

function formatNumber(num) {
  if(! num)return "";
  let [int, float] = num.split(".");
  let intArr = int.split("");
  let result = [];
  let i = 0;
  while (intArr.length) {
    if(i ! = =0 && i % 3= = =0) {
      result.unshift(intArr.pop() + ",");
    } else {
      result.unshift(intArr.pop());
    }
    i++;
  }
  return result.join("") + "." + (float ? float : "");
}
Copy the code

14,map,find,every,some,forEachWhat is the second argument to the etc method?

arr.every(callback(element[, index[, array]])[, thisArg])
Copy the code
  • thisArg

The this value used when executing callback.