Front-end stylus test questions

1. Convert multidimensional array to one-dimensional array

let firstArr = [1, [2, [[3, 4], 5], 6]]

1.1 Using recursion

Idea: loop through each item of the array, if it is an array type, recurse, otherwise, put it in a new array


    let finalArr = []

    function deepArr(a) {
    
    

      for (let i = 0; i < a.length; i++) {
    
    
        if (Array.isArray(a[i])) {
    
    
          deepArr(a[i])
        } else {
    
    
          finalArr.push(a[i])
        }
      }
    }
    deepArr(firstArr)
    console.log(finalArr)

1.2 Using the array reduce method

The array reduce method contains four parameters:

  • perviousValue: the return value of the last calculation result
  • currentValue: The element in the array being processed. If an initial value is specified, the value is the element at index 0 of the array, otherwise 1
  • currentIndex: The index of the element in the array being processed. If an initial value is specified, the starting index is 0, otherwise 1
  • array: array of objects to be traversed

initialValue (optional): This parameter is used as the value of the parameter previousValue when the function is called for the first time.
If the initial value initialValue is specified, currentValue will use the first element of the array;
otherwise, previousValue will use the first element of the array, and currentValue will use the second element of the array

 const flatten = arr => arr.reduce(
      (acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []
    )
    console.log(flatten(arr))

1.3 Use join, split

Idea: Convert the array to a string, and then convert it back
Problem: After conversion, the elements are all string types

 let finalArr=arr.join(',').split(',')
    console.log(finalArr)

1.4 Using apply

Problem: Only two-dimensional arrays can be changed to one-dimensional

const arr = [1,[2,3],[4,5]];
console.log([].concat.apply([],arr));

2 Array deduplication

let arr=[11,22,33,44,55,66,77,88,33,22,44,11]

2.1 Use the new set collection of es6

let final=new Set(arr)

2.2 Using indexOf can only find the subscript that appears for the first time

let newArr=[]

let newArr = arr.filter((item, index) => {
    
    
     return arr.indexOf(item) == index
    })

2.3 for loop + indexOf

indexOf (or includex) to determine whether the new array exists, if not, then push


  function duplicate(arrT) {
    
    
      let newArr = []
      for (let i = 0; i < arrT.length; i++) {
    
    
        if (newArr.indexOf(arrT[i]) == -1) {
    
    
          newArr.push(arrT[i])
        }
      }
      return newArr
    }
   console.log( duplicate(arr))

2.4 Double for loop

  function noRepeat(arr) {
    
    
        for(var i = 0; i < arr.length-1; i++){
    
    
            for(var j = i+1; j < arr.length; j++){
    
    
                if(arr[i]===arr[j]){
    
    
                    arr.splice(j,1);
                    j--;
                }
            }
        }
        return arr;
 }
 console.log(noRepeat(arr12))

3. Handwriting class

3.1 Anti-shake

After the event is triggered, the function is only executed once within n seconds. If the event is retriggered within n seconds, the execution time of the function will be recalculated.
Scenario: login, submit button, send SMS, etc. to prevent multiple submissions

function debounce(fn, wait) {
    
    
            var timeout = null;
            return function() {
    
    
                if(timeout !== null)
                    clearTimeout(timeout);
                timeout = setTimeout(fn, wait);
            }
        }
        // 处理函数
        function handle() {
    
    
            console.log(Math.random());
        }
        // 滚动事件
        window.addEventListener('scroll', debounce(handle, 1000));

3.2 Throttling

Idea: Guarantee that it is executed only once within a certain period of time, and return if an event is being executed.
Scenes:

  • The mouse triggers an event (such as click) continuously, only once per unit time
  • Monitor browser resize
   function throttle(fn, delay) {
    
    
            let canRun = true; // 通过闭包保存一个标记
            return function () {
    
    
                // 在函数开头判断标记是否为true,不为true则return
                if (!canRun) return;
                // 立即设置为false
                canRun = false;
                // 将外部传入的函数的执行放在setTimeout中
                setTimeout(() => {
    
    
                    // 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。
                    // 当定时器没有执行的时候标记永远是false,在开头被return掉
                    fn.apply(this, arguments);
                    canRun = true;
                }, delay);
            };
        }

        function sayHi(e) {
    
    
            console.log('节流:', e.target.innerWidth, e.target.innerHeight);
        }
        window.addEventListener('resize', throttle(sayHi, 500));

3.3 The longest substring without repeated strings (ants)

example:

 input: abcabcbb    output: 3
 input: bbbbb       output: 1
 input: iwwkee      output : wke 3

Implement it yourself:

  function solution(str){
    
    
            let finalSet=new Set()
            let finalLength=0
            for(let i=0;i<str.length;i++){
    
    
                if(!finalSet.has(str[i])){
    
    
                    finalSet.add(str[i])
                    finalLength++
                }
                
            }
            return finalLength
        }
        let s='asdftya'
        console.log(solution(s))

Reference answer:


        function solution(str: string): number {
    
    
            let set = new Set()
            let length = 0
            let maxLength = 0
            for (let i = 0; i < str.length; i++) {
    
    
                if (!set.has(str[i])) {
    
     //不存在
                    set.add(str[i])
                    length++
                } else {
    
     //存在
                    maxLength = Math.max(maxLength, length)
                    length = 0
                }
            }
            return maxLength
        }

3.4 Given a two-dimensional array, convert it to an object (Dharma Academy)

     Input : [
            ["John", 12],
            ["Jack", 13],
            ["Matt", 14],
            ["Maxx", 15]
        ]

       Output : {
    
    
            "John": 12,
            "Jack": 13,
            "Matt": 14,
            "Maxx": 15
        }

accomplish:

 function handleArr(arr) {
    
    
            let finalObj={
    
    }
            for (let i = 0; i < arr.length; i++) {
    
    
                let item = arr[i]
                finalObj[item[0]]=item[1]
            }
            return finalObj
        }
   console.log(handleArr(Input))

insert image description here

3.5 Handwritten promises

3.6 Handwritten instanceof

b instance a: Determine whether b is an instance of a
, namely: the prototype of b points to the prototype
implementation of a:

   //迭代实现
        function instanceOf(obj, constructor) {
    
    
            //取constructor的原型
            let prototype = constructor.prototype;
            //取obj的原型
            obj = obj.__proto__;
            while (true) {
    
    
                if (obj === prototype)
                    return true;
                obj = obj.__proto__;
                if (obj === null)
                    return false;
            }
        }

3.7 Deep Copy

1. Object.assign (empty object name, object name to be copied)
one-level implementation (deep copy), 2. Multi-layer implementation (shallow copy))
insert image description here
2. JSON.parse
function, undefined cannot be copied
insert image description here
3. Handwritten method

JSON.parse(JSON.stringify())
 function deepClone(obj) {
    
    
            if (typeof obj !== 'object') {
    
    
            //简单数据类型直接返回
                return obj
            }
            let newObj = {
    
    }
            for (let i in obj) {
    
    
                newObj[i] = deepClone(obj[i])
            }
            return newObj
        }

Upgraded version:

function deepClone(obj) {
    
    
      if (obj === null) return null; //null 的情况
      if (obj instanceof RegExp) return new RegExp(obj); //正则表达式的情况
      if (obj instanceof Date) return new Date(obj); //日期对象的情况
      if (typeof obj == 'Function') return new function(obj){
    
    }; //函数的情况
      if (typeof obj != "object") {
    
    
        //非复杂类型,直接返回 也是结束递归的条件
        return obj
      }
      //[].__proto__.constructor=Array()  []
      //{}.__proto__.constructor=Object()  {}
      //因此处理数组的情况时,可以取巧用这个办法来new新对象
      var newObj = new obj.__proto__.constructor;
      for (var key in obj) {
    
    
        newObj[key] = deepClone(obj[key])
      }
      return newObj;
    }

3.8 Vault (Byte Two Sides)

insert image description here
code:

 // 注意象棋棋盘是7 * 7,然后象棋每次跳日
        // let count = 0
        function solution(x0, y0, xn, yn, n) {
    
    
            // 递归出口
            if (n == 0) {
    
    
                if (x0 == xn && y0 == yn) {
    
    
                    // count++
                    return 1
                }
                return 0
            }
            let arr = getNextSteps(x0, y0)
            let sum = 0
            console.log(arr);
            for (let i = 0; i < arr.length; i++) {
    
    
                sum += solution(arr[i][0], arr[i][1], xn, yn, n - 1)
            }
            return sum
        }
        let c = solution(0, 0, 5, 6, 5)
        // console.log(count);
        console.log(c);
        // 用于判断它的下一步跳的情况,在最中间时一共有8种跳跃情况
        function getNextSteps(x, y) {
    
    
            let arr = []
            // 往第一象限跳
            if (x <= 4 && y >= 1) {
    
    
                arr.push([x + 2, y - 1])
            }
            if (x <= 5 && y >= 2) {
    
    
                arr.push([x + 1, y - 2])
            }
            // 往第二象限跳
            if (x >= 2 && y >= 1) {
    
    
                arr.push([x - 2, y - 1])
            }
            if (x >= 1 && y >= 2) {
    
    
                arr.push([x - 1, y - 2])
            }
            // 往第三象限跳
            if (x >= 2 && y <= 5) {
    
    
                arr.push([x - 2, y + 1])
            }
            if (x >= 1 && y <= 4) {
    
    
                arr.push([x - 1, y + 2])
            }
            // 往第四象限跳
            if (x <= 4 && y <= 5) {
    
    
                arr.push([x + 2, y + 1])
            }
            if (x <= 5 && y <= 4) {
    
    
                rr.push([x + 1, y + 2])
            }
            return arr
        }
// let arr = getNextSteps(0, 0)
// console.log(arr);

3.9 Get url parameters

Given a url:
"http://www.baidu.com?name=Zhangsan&age=25&sex=male&wife=Xiaohong"
output image result:
insert image description here

 let URL = "http://www.baidu.com?name=张三&age=25&sex=男&wife=小红"
        function getUrlParams(url) {
    
    
            // 通过 ? 分割获取后面的参数字符串
            let urlStr = url.split('?')[1]
            // 创建空对象存储参数
            let obj = {
    
    };
            // 再通过 & 将每一个参数单独分割出来
            let paramsArr = urlStr.split('&')
            for (let i = 0, len = paramsArr.length; i < len; i++) {
    
    
                // 再通过 = 将每一个参数分割为 key:value 的形式
                let arr = paramsArr[i].split('=')
                obj[arr[0]] = arr[1];
            }
            return obj
        }
        console.log(getUrlParams(URL))

        function handleUrl(u) {
    
    
            let urlStr = u.split('?')[1]
            let paramArr = urlStr.split('&')
            let final = []
            for (let i = 0; i < paramArr.length; i++) {
    
    
                let item = paramArr[i].split('=')
                final.push(item[0])
            }
            return final
        }
        console.log(handleUrl(URL))

3.10 The first character that appears only once (Meituan)

Find the first character that appears only one in a long string, and return its position, if not, return -1 (case sensitive), counting from 0.

Data range: 0<=n<=10000, and the string consists of only letters
Requirements: space complexity O(n), time complexity O(n)

Example:

输入 :"google"
输出:4

输入:"aa"
输出:-1

code:

function handleFirst(s) {
    
    
            for (let i = 0; i < s.length; i++) {
    
    
                a = s.indexOf(s[i])
                b = s.indexOf(s[i], a + 1)
                if (b == -1) {
    
    
                    return i;
                }

            }
            return -1;
        }

3.11 Determine whether the brackets are valid (Meituan)

Guess you like

Origin blog.csdn.net/weixin_44247866/article/details/127575470