Come and do two front-end interview questions when you are free. You are the next big man (summary)

Keywords: Javascript Interview

From the column "front end interview questions"

preface

❤️ Author home page: https://hongweblog.blog.csdn.net/

❤️ Introduction: there is no lofty ideal. Just do what you like~

❤️ Scan code concerns WeChat official account: > Dianc assistant

❤️ Front end learning roadmap, interview question brushing, collection of two-dimensional wallpaper, and Dianc assistant will continue to improve in the follow-up.

❤️ Your active participation and discussion is the driving force for Dianc to push more high-quality content~

25 days apart

This issue finally ushers in the summary. This article is a little special. Some time ago, because the js code is not displayed in the form of pictures, the workload has become larger, and the effect is not very good. Therefore, it is planned to send it in the form of pictures later, and the interview questions in the next issue will be written in the test center of css/html.

This time, it is mainly handwritten code, and the little partner can copy it by himself. At the same time, because the release time of each article is not unified, the problem-solving ideas are not very accurate. If the little partner can find it in time, please point it out in time and I will modify it in time~

First question

<script>
        // Use the recursive form to flatten the array
        var a = [1, [2, [3, 4, 5]]]
        function flatten(arr) {
            let result = []
            for (var i = 0; i < arr.length; i++) {
                if (Array.isArray(arr[i])) {
                    result = result.concat(flatten(arr[i]))
                }
                else {
                    result.push(arr[i])
                }
            }
            return result;
        }
        console.log(flatten(a)); //[1,2,3,4,5]
    </script>

Problem solving ideas

First of all, we should understand what flattening means. As the name suggests, it is to reduce the complexity decoration, make the things themselves more concise and simple, and highlight the theme. That is to remove the redundant nesting. The recursive judgment condition is to end if it is not an array and throw out the answer, that is, a flattened array.

Second question

<script>
        // Say the print results below and explain why

        let a = { n: 1 };
        let b = a;
        a.x = a = { n: 2 };

        console.log(a.x)
        console.log(b.x)
    </script>

Problem solving ideas

This problem involves the priority of assignment. a.x has higher priority than the assignment of equal sign, so a.x will be assigned as {n:2}, and then the pointer of a will be changed into {n:2}. Therefore, a.x originally has a value. If it is not found in the later assignment, it will output undefined.

Question 3

<script>
        // Say the following print results

        const obj = { 1: 'a', 2: 'b', 3: 'c' }
        const set = new Set([1, 2, 3, 4, 5])

        console.log(obj.hasOwnProperty('1'))
        console.log(obj.hasOwnProperty(1))
        console.log(set.has('1'))
        console.log(set.has(1))

    </script>

Problem solving ideas

The hasOwnProperty() method will return a Boolean value indicating whether there is a specified property (that is, whether there is a specified key) in the object's own property. At the same time, the property name in the object defaults to object rendering, so the first line should output true, and then the following has() Method indicates whether the Set object contains the specified value. If the specified value exists, it returns true; otherwise, it returns false.
After materialization, it will determine whether it is an object or a number, so the third line outputs false.

Question 4

<script>
        // Say the following print results

        const obj = { a: 'one', b: 'two', a: 'three' }
        console.log(obj)
    </script>

Problem solving ideas

This question is not simple. As long as you know that the repetition of the object will be replaced, you will know the answer. There are not many pits, so the answer is output
{a: 'three', b: 'two'}

Question 5

<script>
        // Say the following print results

        for (let i = 1; i < 5; i++) {
            if (i === 3) continue
            console.log(i)
        }
    </script>

Problem solving ideas

for loop needless to say, it's good to distinguish between break and continue here. Break is the end of the loop, and continue jumps out of this loop and will be executed next time. Therefore, 1, 2 and 4 should be output.

Question 6

<script>
        // Say the following print results

        String.prototype.giveLydiaPizza = () => {
            return 'Just give Lydia pizza already!'
        }
        const userName = 'Lydia'
        console.log(userName.giveLydiaPizza())
    </script>

Problem solving ideas

String is a built-in constructor for which we can add properties. I just added a method to its prototype. The original type string is automatically converted to a string object and generated by the string prototype function. Therefore, all strings (string objects) can access this method!

Question 7

 <script>
        // Say the following print results
        var result = [];
        var a = 3;
        var total = 0;
        function foo(a) {
            for (var i = 0; i < 3; i++) {
                result[i] = function () {
                    total += i * a;
                    console.log(total)
                }
            }
        }
        foo(1);
        result[0]();
        result[1]();
        result[2]();

    </script>

Problem solving ideas

First of all, we must see whether the loop variable is a global variable or a local variable. If it is a global variable, it has been calculated during precompiling when calling i, so the i called by function result should be 3. Therefore, total is also a global variable, so it should be 3, 6 and 9 after execution.

Question 8

<script>
        // Say the following print results

        function Person(name) {
            this.name = name;
        }
        function Student() {

        }

        Student.prototype = Person.prototype;
        Student.prototype.constructor = Student;
        var s = new Student('Tom');
        console.log(s instanceof Person);
    </script>

Problem solving ideas

After learning js for so long, I've heard that capitalized initials are generally used as constructors, so the instanceof operator is used to detect whether the prototype attribute of the constructor appears on the prototype chain of an instance object.
So the answer is true;

Question 9

<script>
        for (var i = 0; i < 10; i++) {
            setTimeout(() => {
                console.log(i)
            }, 0)
        }
    </script>

Problem solving ideas

This question is very classic. It can only be said that it is very simple after understanding. When there is setTimeout, you should understand that it is the next macro task, and then because it is a var variable, the i of all calls should be window.i=10, so the above code is printed 10 times.

Question 10

<script>
        for (let i = 0; i < 10; i++) {
            setTimeout(() => {
                console.log(i)
            }, 0)
        }
    </script>

Problem solving ideas

Well, I have provided two methods above. In order to prove that I have no water article, I decided to write the fourth method. You can think about it yourself. Oh, this classic is not realized in these ways.

Question 11

<script>
        console.log('a')

        setTimeout(() => {
            console.log('b')
        }, 0)

        console.log('c')

        Promise.resolve().then(() => {
            console.log('d')
        }).then(() => {
            console.log('e')
        })

        console.log('f')
    </script>

Problem solving ideas

OK, let's start with the answer: a c f d e b;

Specifically, this topic examines the execution sequence of macro tasks and micro tasks. First, let's understand the workflow of macro tasks and micro tasks. In fact, it was also involved yesterday, but we didn't elaborate

Then let's talk about the macro task of this problem, which is normally output console.log. SetTimeout belongs to the next round of macro tasks, that is, it can be executed after the current round of micro tasks are executed. Promise belongs to micro tasks, so setTimeout is the last output

Question 12

<script>
        var a = 2
        var obj = {
            a: 3,
            fn: function () {
                const a = () => {
                    console.log(this.a)
                }
                const b = function () {
                    console.log(this.a)
                }
                a()
                b()
            }
        }

        obj.fn()
    </script>

Problem solving ideas

First say the answer: 3 2;

I don't know if my partner is right. First of all, we need to know the problem of this pointing. Through the problem, we find that there is only the difference between the arrow function and the normal function. It should be clear that this of the arrow function actually points to the parent scope, so this.a should point to a in this object, and the normal function will point to window.

Question 13

<script>
        function side(arr) {
            arr[0] = arr[2];
        }
        function a(a, b, c = 3) {
            c = 10;
            side(arguments);
            return a + b + c;
        }

        console.log(a(1, 1, 1))
    </script>

Problem solving ideas

This question needs to be careful. First, when we execute console.log, we will pass three values to the a function. However, note here that c=3 indicates that a block level scope is created independently, and then looking down, c=10. Well, some partners here should be misled. Will arguments really refer to c=10? The answer is wrong. In fact, when c independently creates a block level scope , arguments will not take this value, but take the passed value 1, 1, 1. Then a and b should be equal to 1, and c should be equal to 10

Question 14

<script>
        var a = [0];
        if (a) {
            console.log(a == true);
        } else {
            console.log(a)
        }

        (function () {
            var a = (b = 5);
        })();

        console.log(b);
        console.log(a);
    </script>

Problem solving ideas

First, when a variable is in if, it will be converted into a Boolean value to judge whether it is true or false. Then, when a==true involves complex types, the comparison is that the pointer points to, and the difference is false, so the first value prints false. Looking back, if a var is defined in the immediate execution function, it can not be accessed outside the scope Yes, but b can be accessed. Because it is a global variable, the second and third values are 5 and [0], and a takes the value defined at the beginning.

Question 15

<script>
        var fullName = 'a';
        var obj = {
            fullName: 'b',
            prop: {
                fullName: 'c',
                getFullName: function() {
                    return this.fullName;
                }
            }
        }

        console.log(obj.prop.getFullName());
        var test = obj.prop.getFullName;
        console.log(test());
    </script>

Problem solving ideas

First, this question examines the direction of this, so we can see that the function is executed directly by the object when the console outputs the first time, so the fullName output for the first time should point to the fullName of the parent prop, that is, c.
The second time is not to directly use the object to execute the function, so it should be translated into window.test(); Then the global fullName is a, so the answer comes out.

Question 16

 <script>
        var foo = {
            bar: function() {
                return this.baz;
            },
            baz: 1
        }
        console.log(typeof(f = foo.bar)());
    </script>

Problem solving ideas

First of all, we need to know that there is () after the output, indicating that the function is to be executed. At this time, we find that f is actually global, so it should be window.f(). Then this of foo.bar should point to window. The attribute of bar cannot be found up, so we should output undefined.

Question 17

<script>
        const num = {
            a: 10,
            add() {
                return this.a + 2;
            },
            reduce: () => this.a - 2
        };
        console.log(num.add());
        console.log(num.reduce());
    </script>

Problem solving ideas

There should be no problem with the output 12 of the add() function. The key lies in what is output by reduce. After careful observation, you will find that the arrow function is not a normal function. this of the arrow function points to the nearest parent. Looking up, there is only window. Therefore, window.a is undefined. Subtracting a non number will get NAN, right.

Question 18 (CSS - Beta)

Let's talk about the understanding of css box model

answer

css box model, also known as box model, contains several elements: content, padding, border and margin.
There are two kinds of box models: standard box model and IE box model.
In the standard box model, width and height refer to the width and height of the content area. Increasing the inner margin, border and outer margin will not affect the size of the content area, but will increase the total size of the element box; However, in IE6, the width of the browser is not the width of the content, but the sum of the width of the content, inner margin and border; The content part of IE contains border and padding.

Question 19

<script>
        let a = {
            name: "jock",
            age: 20
        }

        function change(o) {
            o.age = 24;
            o = {
                name: "alan",
                age: 30
            }
            return o
        }
        let b = change(a)
        console.log(b.age)
        console.log(a.age)
    </script>

Problem solving ideas

This topic mainly focuses on the reference relationship of the object pointer. Then we see that the value of a is passed to change(o), so at this time, the objects of O and a point to the same location, so a.age=o.age=24. Later, the object of O is overwritten again, so at this time, o.age becomes 30

Question 20

<script>
        // TODO: A: foo(){foo=10;console.log(foo)}
        // TODO: B: 1
        // TODO: C: 10
        // TODO: D: undefined

        var foo = 1;
        (function foo() {
            foo = 10;
            console.log(foo);
        }())
    </script>

Problem solving ideas

Note that the immediate execution function here has a name. This question mainly investigates that the user-defined function with a name will create an object attribute value by default, and this attribute value is the function itself (it is read-only and cannot be modified), so the answer is to output this function

last

In fact, the problems of big factories are simple and difficult, and there are even test details. Just like the math test paper when I was young, multiple-choice questions always have points, right? So simple questions must be won, but they can't be taken lightly.
If you still don't understand the above questions, please refer to the problem-solving ideas to review, find out the omissions and fill the gaps. Finally, I wish you all can enter your ideal enterprise!

From previous quality articles

Popular article recommendations:

🥇 In this way, it is difficult to learn VSCode and write front-end code( ❤️ Carefully prepare the hyperactivity diagram. It is recommended to collect it~ ❤️)
🥈 Don't you know how to build a personal blog? Teach you how to use Wordpress to build a world that only belongs to you~
🥉 Preparations for Hexo (teach you how to build Node.js/Git environment by hand)

Posted by magic-eyes on Thu, 07 Oct 2021 13:29:00 -0700