[Step-By-Step] Deep Analysis of High Frequency Interview Questions/Weekly 05

  Front end, html5, javascript, node.js, Programmer

This week’s interview questions list:

  • Implement Promise.race method
  • JSONP Principle and Its Simple Implementation
  • Implementation of an Array De-duplication Method
  • What are the methods of floating?
  • Writing a General currying Function

More quality articles to stamp on: https://github.com/YvetteLau/ …

20. implement Promise.race method

In realizationPromise.raceBefore the method, we first need to knowPromise.raceThe function and characteristics of because in the clearPromise.raceFunctions and characteristics of the case, we can further write to achieve.

Promise.race function

Promise.race(iterable)Returns a promise onceiterableOne of thepromiseStatus isfulfilled/rejected, thenPromise.raceReturnedpromiseStatus isfulfilled/rejected.

let p = Promise.race([p1, p2, p3]);

As long as one of p1, p2 and p3 takes the lead in changing the state, the state of P will change accordingly. The first to changePromiseThe return value of the instance is passed to the callback function of p.

The characteristics of Promise.race

The return value of Promise.race is a promise instance.

  • If the passed-in parameter is an empty iterated object, thenPromise.raceReturnedpromiseAlwayspendingstate
  • If the parameter passed in does not contain anypromise,Promise.raceWill return a pendingpromise
  • IfiterableContains one or more non-s.promiseValue or resolved promise, thenPromise.raceResolve toiterableThe first value found in the.

Implementation of Promise.race

Promise.race = function (promises) {
    promises = Array.from(promises);//将可迭代对象转换为数组
    return new Promise((resolve, reject) => {
        if (promises.length === 0) {
        } else {
            for (let i = 0; i < promises.length; i++) {
                Promise.resolve(promises[i]).then((data) => {
                }).catch((reason) => {

21. JSONP Principle and Simple Implementation

Although browsers have homologous policies, however<script>TaggedsrcAttributes are not constrained by homologous policies, and scripts on any server can be obtained and executed.jsonpBy insertionscriptTag to achieve cross-domain, parameters can only be passed throughurlIncoming, only supportedgetRequest.

Implementation principle:

  • Step1: Create callback Method
  • Step2: Insert script Label
  • Step3: The background receives the request, parses the callback method passed by the front end, returns the call of the method, and the data is passed into the method as a parameter
  • Step4: The front end executes the method call returned by the service end

Jsonp source code implementation

function jsonp({url, params, callback}) {
    return new Promise((resolve, reject) => {
        let script = document.createElement('script');
        //将回调函数挂在 window 上
        window[callback] = function(data) {
        params = {...params, callback} //wb=b&callback=show
        let arrs = [];
        for(let key in params) {
        script.src = `${url}?${arrs.join('&')}`;


function show(data) {
    url: 'http://localhost:3000/show',
    params: {
    callback: 'show'
}).then(data => {


let express = require('express');
let app = express();

app.get('/show', (req, res) => {
    let {callback} = req.query; //获取传来的callback函数名,callback是key

22. Implement an array deduplication method

Method 1: Use ES6 to add new data typesSet

SetIt is similar to an array, but the values of members are unique and there are no duplicate values.

function uniq(arry) {
    return [...new Set(arry)];

Method 2: UseindexOf

function uniq(arry) {
    var result = [];
    for (var i = 0; i < arry.length; i++) {
        if (result.indexOf(arry[i]) === -1) {
            //如 result 中没有 arry[i],则添加到数组中
    return result;

Method 3: Useincludes

function uniq(arry) {
    var result = [];
    for (var i = 0; i < arry.length; i++) {
        if (!result.includes(arry[i])) {
            //如 result 中没有 arry[i],则添加到数组中
    return result;

Method 4: Usereduce

function uniq(arry) {
    return arry.reduce((prev, cur) => prev.includes(cur) ? prev : [...prev, cur], []);

Method 5: UseMap

function uniq(arry) {
    let map = new Map();
    let result = new Array();
    for (let i = 0; i < arry.length; i++) {
        if (map.has(arry[i])) {
            map.set(arry[i], true);
        } else {
            map.set(arry[i], false);
    return result;

23. What are the methods of eliminating floating?

When the height of the container is auto, and the content of the container has floating elements (float is left or right), in this case, the height of the container cannot be automatically extended to adapt to the height of the content, so that the content overflows to the outside of the container and affects (even destroys) the layout. This phenomenon is called floating overflow. CSS processing to prevent this phenomenon is called CSS floating removal.

    .inner {
        width: 100px;
        height: 100px;
        float: left;
<div class='outer'>
    <div class='inner'></div>
    <div class='inner'></div>
    <div class='inner'></div>

1. UtilizationclearAttribute

In<div class='outer'>Create an empty element in theclear: both;The style of.

  • Advantages: simple, less code, good browser compatibility.
  • Disadvantages: Need to add a large number of non-semantic html elements, the code is not elegant enough, and it is not easy to maintain later.

2. UtilizationclearAttribute+Pseudo Element

    content: '';
    display: block;
    clear: both;
    visibility: hidden;
    height: 0;

IE8+and non-IE browsers only support: after, if you want to support IE6 and 7, you need to giveouterElements, setting styleszoom: 1;

3. Use BFC layout rules

According to BFC rules, floating elements also participate in the calculation when calculating the height of BFC. Therefore, only one BFC needs to be triggered to clear the float.

The following methods can be used to trigger BFC

  • Position is absolute or relative.
  • Overflow is not a visible block element
  • Display is inline-block, table-cell, table-capture.

For example:

.outer {
    overflow: hidden;

Pay attention to usedisplay: inline-blockThere will be gaps.

24. Write a general currying function

Before we begin, we first need to make clear the concept of function kriging.

Corellization of functions is a technique that transforms a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returns a new function that accepts the remaining parameters and returns the result.

const currying = (fn, ...args) =>
    args.length < fn.length
        ? (...arguments) => currying(fn, ...args, ...arguments)
        : fn(...args);
function sumFn(a, b, c) {
    return a + b + c;
var sum = currying(sumFn);
console.log(sum(2, 3, 5));//10
console.log(sum(2)(3, 5));//10
console.log(sum(2, 3)(5));//10

The Main Functions of Curriculation of Functions;

  • Parameter reuse
  • Return in advance–returns a new function that accepts the remaining parameters and returns the result
  • Delayed execution–returns a new function and waits for execution

Reference articles:

[1]CSS- clear float

[2]The detailed explanation JS function Corellization

[3]JavaScript array deduplication

Thank you for your friends’ willingness to spend precious time reading this article. If this article gives you some help or inspiration, please don’t be stingy with your praise and Star. Your affirmation is my greatest motivation to move forward.https://github.com/YvetteLau/ …

Recommend to pay attention to my public number: