interview(-)

0. Scope

Consider the following code:

 

1 (function(){
2    var a = b = 5;
3 })()
4 
5 console.log(b)

 

What will the console print?

Answer

The above code prints out 5

The pitfall of this problem is that in the immediately executed function expression, there are two assignments, but the variable a is declared with the keyword var . This means that a is a local variable of this function. In contrast, b is assigned the global scope.

Another gotcha, the function doesn't use "strict mode". If strict mode is on, the code will report the error "b is not defined". Keep in mind that strict mode requires you to explicitly reference the global scope if this is expected behavior. Need to write like this:

 

1 (function(){
2     "use strict";
3      var a = window.b = 5; 
4 })()
5 
6 console.log(b)

 

1. Create "native" methods

Define a repeatify function on the String object . This function accepts an integer parameter to specify how many times the string needs to be repeated. This function asks the string to repeat the specified number of times. Example:

console.log("hello".repeatify(3));

should print hellohellohello

Answer

Possible practices are as follows:

1 String.prototype.repeatify = String.prototype.repeatify || function(times){
2 var str = '';
3   for(var i=0;i<times;i++){
4      str += this;  
5   }      
6   return str;
7 }

This question tests the developer's knowledge of inheritance and prototype properties in JavaScript. This also verifies that developers have the ability to extend the functionality of native data types.

Another key point here is to see how you can avoid overriding methods that may already be defined. This can be done by checking if a method already exists before defining your own method.

1 String.prototype.repeatify = String.prototype.repeatify || function(times){
2 /*code here*/
3 }

2. Variable promotion

What is the result of executing the following code? Why?

 1 function test(){
 2    console.log(a);
 3    console.log(foo());
 4 
 5    var a= 1;
 6    function foo(){
 7       return 2;    
 8   }  
 9 }
10 test();

Answer

The execution result of this code is undefined and 2.

The reason for this result is that both variables and functions are hoisted to the top of the function ensemble. So when the variable a is printed . Although it exists in the function body, it is still undefined. In other words, the above code is equivalent to the following code:

function test(){
  var a;
  function foo(){
    return 2;
  }  
  console.log(a);
  console.log(foo());

  a=1;
}
test()

3. How "this" works in JavaScript

What is the result of the following code? Explain your answer.

 

 1 var fullname = 'John Doe';
 2 var obj = {
 3    fullname:'Colin Ihrig',
 4    prop:{
 5          fullname:'Aurelio De Rosa',
 6          getFullname:function(){
 7              return this.fullname;  
 8          }  
 9     }  
10 }
11 console.log(obj.prop.getFullname()); 
12 var test = obj.prop.getFullname;
13 console.log(test());

 

The print is: Aurelio De Rosa and   John Doe . Because the keyword this in JavaScript refers to the function context, it depends on how the function is called, not how it is defined.

In the first console.log(), getFullname() is called as a function of the obj.prop object. Therefore, the current context refers to the latter, and the function returns the fullname property of this object. But when getFullname() is assigned to the test variable, the current context is the global object window, because test is implicitly a property of the global object. Based on this, the function returns the fullname of the window, set by the first line of code.

 

 

 4.call() and apply()

Modify the previous question to have the last console.log(test ()) print out Aurelio De Rosa .

This problem can be applied to the call() or apply() method to force the context.

 

console.log(test.call(obj.prop));

 

5. Closures

What is the result of the following code, please explain.

1  var count = 10 ; //The global scope is marked as flag1
 2  function add(){
 3    var count = 0 ; //The function global scope is marked as flag2
 4    return  function (){
 5       count+=1 ; //The function's inner scope
 6       alert(count)
 7    }  
 8  }
 9  var s = add();
 10  s();
 11 s();

The first s() outputs 1 and the second s() outputs 2 .

According to the rules of the scope chain, the variable that is not declared in the underlying scope will be searched for the upper level, if found, it will return. that count.

Definition: When the return value of a function is another function, and the returned function calls other variables inside its parent function, if the returned function is executed outside, a closure is generated.

Representation: Enables the outside of the function to call the variables defined inside the function.

Scope classification of variables: global variables and local variables

Features:

1. Global variables outside the function can be read inside the function; local variables inside the function cannot be read outside the function.

2. When declaring variables inside a function, be sure to use the var command. If you don't use it, you're actually declaring a global variable.

Note on using closures:

1. Abusing closures will cause memory leaks. Since closures will keep variables in functions in memory and consume a lot of memory, closures cannot be abused, otherwise it will cause performance problems of web pages, and memory may be caused in IE. leakage. The solution is to delete all unused local variables before exiting the function.

2. Will change the value of the internal variable of the parent function. So, if you use the parent function as an object, the closure as its public method, and the internal variable as its private property, be careful not to change the value of the variable inside the parent function.

 6. Data Types

Consider the following code:

 

1 console.log(typeof null);
2 console.log(typeof {});
3 console.log(typeof []);
4 console.log(typeof undefined);

 

Answer

Examine your knowledge of the typeof operator. Many JavaScript developers are unaware of some features of typeof. The console will display the following:

1 object
2 object
3 object
4 undefined

The most surprising output is probably the third one. Most developers think that typeof() returns Array. If you want to test if a variable is an array, you can perform the following test:

1 var myArray = [];
2 if(myArray instanceof Array){
3       //do something
4 }

7. Event Loop

What is the result of running the following code? please explain.

1 function printing(){
2     console.log(1);
3     setTimeout(function(){console.log(2)},1000);
4     setTimeout(function(){console.log(3)},0);
5     console.log(4);
6 }
7 printing();

Answer

Output result:

1
4
3
2

To understand why the output order is like this, you need to understand what setTimeout() does, and how the browser's event loop works. The browser has an event loop that checks the event queue and handles deferred events. UI events (eg, click, scroll, etc.), Ajax callbacks, and callbacks provided to setTimeout() and setInterval() are in turn handled by the event loop. Therefore, when the setTimeout() function is called, even if the delay time is set to 0, the provided callbacks will be processed in turn by the event loop. The callback will stay in the queue until the specified time has elapsed and the engine will start executing the action (if it is not currently executing other actions). So even if the setTimeout() callback is delayed by 0 milliseconds, it will still be queued and will not be executed until other non-delayed statements in the function have been executed.

With this knowledge, it is easy to understand that the output is "1" because it is the first sentence of the function and there is no delay using the setTimeout() function. Then "4" is output because it is a number that is not delayed and is not queued. Then, "2", "3" are left, both are queued, but the former needs to wait one second, the latter waits 0 seconds (meaning that the engine will do it right after the first two outputs are done). This explains why "3" comes before "2".

8. Algorithms

Write an isPrime() function that returns true if it is a prime number, and false otherwise.

Answer

First, because JavaScript is different from c or java, you can't trust the data type passed. If the interviewer doesn't tell you explicitly, you should ask him if he needs to do input checking or write functions without checking. Strictly speaking, the input to the function should be checked.

Second point to remember: negative numbers are not prime numbers. Likewise, 1 and 0 are not, so test those numbers first. Also, 2 is the only even number among prime numbers. There is no need to use a loop to verify 4, 6, 8. Again, if a number is not divisible by 2, then it is not divisible by 4, 6, 8, etc. Therefore, your loop has to skip these numbers. If you test for an even number of inputs, your algorithm will be 2 times slower. There are other more sensible optimizations that can be taken, but the one used here will work in most cases. For example, if a number is not divisible by 5, it is also not divisible by multiples of 5. So, there is no need to detect 10, 15, 20, etc.

As a final note, you don't need to check numbers larger than the root of the entered number.

 1 function isPrime(number){
 2    if(typeof number !== 'number' || !Number.isInteger(number)){
 3          return false;
 4     }
 5     if(number < 2){
 6          return false;
 7    }
 8    if(number === 2){
 9         return true;
10    }else if(number % 2 === 0){
11         return false;
12    }
13 
14    var squareRoot = Math.sqrt(number);
15    for(var i=3;i<=squareRoot;i+=2){
16       if(number % i === 0){
17              return false;
18       }
19   }  
20   return true;
21 }

Original: http://www.css88.com/archives/7052

 

Guess you like

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