js written test questions

first question

    console.log(a)       //       undefined
    var a = 1;
    var getNum = function() {
        a = 2;
    }
    function getNum() { a = 3; } console.log(a) // 1 getNum() console.log(a) // 2 

This question mainly examines the two knowledge points of declaration hoisting and function declaration before variable declaration . When parsing this js fragment is in this order:

// 声明提升
function getNum() {
    a = 3;
}
var a;
var getNum;

// 
console.log(a);
a = 1;
getNum = function() { a = 2; } console.log(a) getNum() console.log(a) 

This is very clear. When a is output for the first time, it is only declared and has not been assigned, so yes undefined. Needless to say the second time. The third output of 2 is because the variable declaration cannot override the function declaration. It first getNumpoints to a function, and then assigns it to a function expression, which points to another function.

Question 2

// 每隔一秒输出一次i值
for(var i = 0; i < 5; i++){
    // TODO
}

This question mainly examines the closure and js execution mechanism . The following solutions:

A version that outputs about once a second:

// 利用立即执行函数形成闭包
(function(i){
    setTimeout(function() {
        console.log(i)
}, i * 1000)})(i)
// 利用setTimeout的第三个参数形成闭包
setTimeout(function(i) {
    console.log(i)
}, i * 1000, i)
// 如果不是题目中指定了var,利用ES6的let就简单多了
for(let i = 1; i < 5; i++) {
    setTimeout(function(){ console.log(i) }, i * 1000) } 
// 再看ES7版本
const sleep = (time) => 
    new Promise((resolve, reject) => 
        setTimeout(resolve, time));
(async function(){
   for(var i = 0; i < 5; i++){
       await sleep(1000);
       console.log(i);
   }
})()

The reason why it is said to be approximate is because it is setTimeoutnot how many seconds after the delay to execute the function, but how many seconds after the function is thrown into the event queue to wait for execution, if there are other tasks in the queue at this time, it is not exactly 1 second .

Regarding the js execution mechanism, see here this time, thoroughly understand the JavaScript execution mechanism

Let's look at the more precise 1-second version:

for(var i =0; i < 5; i++) {
    var time = new Date();
    while(new Date() - time < 1000) {
    }
    console.log(i)
}

Block the thread directly for one second, simple and rude~

Question 3

var a = {}
var b = {
    key: "a" 
}
var c = {
    key: "c"
}

a[b] = "123";
a[c] = "456";

console.log(a[b])  // 456

This question mainly examines the object . In fact , b and c in here a[b]and in will be called , and they have become , so it has nothing to do with the key value in the object. So the points of and are the same.a[c]object.prototype.toString()[object Object]a[b]a[c]

Question 4

var f = function() {
    var c = "ccc";
    return {
        a: function() { return c; }, b: function(d) { c = d; } } }() console.warn(f.a()) // ccc console.warn(f.c) // undefined console.warn(f.b("www")) // undefined console.warn(f.a()) // www 

This question mainly examines the scope chain in the execution context . We should pay attention to the function executor after the function expression - (), it is an immediate execution function, that is to say, f is an object containing a and b attributes.

console.warn(f.a()) 

When the execution context of a() is activated, the scope and variable object are determined, c is a free variable and needs to be searched up in the scope chain, but it is found in the parent scope, so "ccc" is output.

console.warn(f.c)

Needless to say, there is no attribute c in f, and if you can't get it, you will of course return undefined.

console.warn(f.b("www"))

As in the first line, the c in the parent scope is modified, but since there is no return value, the output is undefined.

Question 5

Array deduplication input is [1,2,3,1,'1','2',2]returned [1,2,3,'1','2']. There are many ways to do this.

(function(arr){
    console.log([...(new Set(arr))])
})([1,2,3,1,'1','2',2])

Using the feature that the key of the Map structure can be of any type, the character '1' and the number 1 can be well distinguished, while the key value of an ordinary object is a string type, which cannot be distinguished between the two.

(function(arr) {
    let hash = new Map();
    arr = arr.reduce((item, value) => {
        hash.has(value) ? '' : hash.set(value, true) && item.push(value) return item; }, []) console.log(arr) })([1,2,3,1,'1','2',2]) 

Question 6

There are two lowercase strings s1 and s2, s2 is obtained by adding a lowercase character after scrambled s1, and programming to get the added characters in s2, the algorithm time complexity is best close to O(n) (for example, s1 is 'abc' ', s2 is 'cbad', then the added character is 'd').

Solution one

The author's thinking on this question, first of all, considering that the added characters may already exist in s1, then indexOf()the solution of traversing + is useless, so the author considers that s1 and s2 only have only s1 and s2 when writing this question For the difference of one character, simply fill in the characters in s1 and s2 into one object, and count the number of each character. The odd number is the extra character. (Also welcome to give a better solution in the comment area) The code above:

var s1 = "aaabweddccc";
var s2 = "aaaewwbcccdd";
(function(a,b){           
    let all = a + b;
    let allLen = all.length; let hash = {}; for(let i = 0; i < allLen; i++) { hash[all[i]] ? hash[all[i]]++ : hash[all[i]] = 1; } console.log(hash) for(let j in hash) { if(hash[j] % 2 !== 0) { console.log(j) } } })(s1,s2) 

operation result:

 

 

Solution two

This method came to mind later. The idea is this, if the extra character is not inserted, after sorting the two strings, the characters in the corresponding positions of the two strings must be the same, and after inserting a character, there must be a position where the characters do not match.

(function(a,b){           
    a = a.split("").sort()
    b = b.split("").sort()
    for(let i = 0, len = b.length; i < len; i++) { if(a[i] !== b[i]) console.log(b[i]) } })(s1,s2) 

operation result:

 

 

Summarize

There are a total of 6 questions, the basics of the test, including:

  • claim boost
  • Closure
  • execution context
  • js execution mechanism
  • ......

Author: Gesangs
Link: https://juejin.im/post/5abaeecef265da237a4d0e20
Source: Nuggets The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324981820&siteId=291194637