You need to know 25 JavaScript face questions _javascript tips

Source: Internet
Author: User
Tags closure mixed object object variable scope

1, the use of typeof bar = = "Object" to determine whether bar is an object God horse potential drawbacks? How to avoid this kind of malpractice?

The drawbacks of using TypeOf are obvious (this disadvantage is with the use of instanceof):

Let obj = {};
Let arr = [];

Console.log (typeof obj = = ' object '); True
console.log (typeof arr = = ' object ');//true
Console.log (typeof null = = ' object ');//true

From the output above, typeof bar = = "Object" does not accurately determine that bar is an object. You can avoid this disadvantage by Object.prototype.toString.call (bar) = = = "[Object Object]":

Let obj = {};
Let arr = [];

Console.log (Object.prototype.toString.call (obj)); [Object Object]
console.log (Object.prototype.toString.call (arr));//[object Array]
console.log ( Object.prototype.toString.call (null)); [Object Null]

In addition, to cherish life, please stay away from = =:

and [] = = False is returned false.

2, the following code will be in the console output God horse? Why?

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

Console.log ("a defined?" + (typeof a!== ' undefined ')); 
Console.log ("B defined" + (typeof b!== ' undefined '));

This is related to the variable scope, and the output is replaced by the following:

Console.log (b); 3
Console,log (typeof a);//undefined

To disassemble a variable assignment in a self-executing function:

b = 3;
var a = b;

So b becomes a global variable, and a is a local variable of the self executing function.

3, the following code will be in the console output God horse? Why?

var myObject = {
 foo: ' Bar ',
 func:function () {
 var self = this;
 Console.log ("outer func:this.foo =" + This.foo);
 Console.log ("outer func:self.foo =" + Self.foo);
 (function () {
 console.log ("Inner Func:this.foo =" + This.foo);
 Console.log ("Inner Func:self.foo =" + Self.foo);
 } ());
 }
};
Myobject.func ();

The first and second outputs are not difficult to judge, before ES6, JavaScript had only a function scope, so the Iife in Func had its own independent scope, and it could access self in the external scope, so the third output would be an error, because this would be the U in the accessible scope ndefined, the fourth output is bar. If you know the closure, it's easy to fix:

(function (test) {
 Console.log ("Inner Func:this.foo =" + Test.foo); ' Bar '
 console.log ("Inner Func:self.foo =" + Self.foo);
} (self));

If you are unfamiliar with closures, you can refer to this article: talking about closures from the scope chain

4, the JavaScript code contained in a block of functions God horse meaning? Why did you do that?

In other words, why use an immediate execution function expression (immediately-invoked function Expression).

Iife has two more classic usage scenarios, one is similar to timing output data items in a loop, and the second is similar to Jquery/node plug-in and module development.

for (var i = 0; i < 5; i++) {
 settimeout (function () {
 console.log (i); 
 }, 1000);
}

The above output is not the 0,1,2,3,4 you think, and the output is all 5, then iife can be useful:

for (var i = 0; i < 5; i++) {
 (function (i) {
 settimeout (function () {
 console.log (i); 
 }, 1000);
 }) (i)
}

And in the Jquery/node plug-in and module development, in order to avoid variable pollution, is also a big iife:

(function ($) { 
 //Code
 }) (JQuery);

5, in strict mode (' use strict ') under the JavaScript Development of God horse benefits?

Eliminate some of the unreasonable and imprecise JavaScript grammar, reduce some of the strange behavior;
Eliminate some unsafe code running, ensure the safety of code operation;
Improve compiler efficiency, increase running speed;
Pave the ground for a new version of JavaScript in the future.
6, the following two functions return values are the same? Why?

function foo1 ()
{return
 {
 bar: ' Hello '
 };
}

function Foo2 ()
{
 return
 {
 bar: ' Hello '
 };
}

In programming languages, the basic use of semicolons (;) to separate statements, which can increase the readability and cleanliness of the code. In JS, if the statement each occupies a separate line, you can usually omit the semicolon (;), the JS parser will be based on whether the normal compilation to determine whether the full number of automatically fill:

var test = 1 + 
2
console.log (test);//3

In the above case, in order to correctly parse the code, it will not automatically fill in the full number, but for return, break, continue, and so on, if the following line, the parser will automatically fill in the full number (;), so the second function on the top becomes this:

function Foo2 ()
{return
 ;
 {
 bar: ' Hello '
 };
}

So the second function is to return undefined.

7, God Horse is NaN, it is the type of God horse? How do I test whether a value is equal to NaN?

NaN is the abbreviation for not a number, a special numeric value of JavaScript, and the type is isNaN (param) to determine whether a value is NaN:

Console.log (isNaN (NaN)); True
Console.log (isNaN),//false
console.log (isNaN (' DS ')),//true
console.log (' 32131SDASD ')); True
console.log (nan = = nan);//false
console.log (nan = = undefined);//false
Console.log ( undefined = = = undefined); False
Console.log (typeof nan);//number
Console.log (Object.prototype.toString.call (Nan));//[object Number]

In ES6, isNaN () becomes a static method of number: Number.isnan ().

8, explain the output of the following code

Console.log (0.1 + 0.2); 0.30000000000000004
Console.log (0.1 + 0.2 = = 0.3);//false

The number type in JavaScript is floating-point, and floating-point numbers in JavaScript are in the form of IEEE-754, a binary notation that accurately represents fractions, such as 1/2,1/8,1/1024, with 64 bits per floating point. However, binary floating-point notation does not accurately represent a simple number like 0.1, with rounding errors.

Because of the binary, JavaScript can not be limited to represent 1/10, 1/2, such as the score. In binary, 1/10 (0.1) is represented as 0.00110011001100110011 ... Note that 0011 is infinitely repetitive, which is caused by rounding errors, so for operations like 0.1 + 0.2, the operands are first converted to binary and then computed:

0.1 => 0.0001 1001 1001 1001 ... (Infinite Loop)
0.2 => 0.0011 0011 0011 0011 ... (Infinite Loop)
The decimal portion of a double-precision floating-point number supports up to 52 digits, so the two add up to a string of 0.0100110011001100110011001100110011001100 ... Binary digits truncated because of the limit of floating-point numbers, which is then converted to decimal, which is 0.30000000000000004.

There are two common ways to ensure the correctness of floating point counting.

First, Huang and then lower power:

function Add (NUM1, num2) {Let
 r1, R2, M;
 R1 = (' +num1 '). Split ('. ') [1].length;
 r2 = (' +num2 '). Split ('. ') [1].length;

 m = Math.pow (10,math.max (R1,R2));
 Return (NUM1 * m + num2 * m)/m;
}
Console.log (Add (0.1,0.2)); 0.3
Console.log (Add (0.15,0.2256));//0.3756

The second is to use the built-in toprecision () and toFixed () methods, note that the method returns a string of values.

function add (x, y) {return
 x.toprecision () + y.toprecision ()
}
Console.log (Add (0.1,0.2));//"0.10.2"

9, the Implementation function Isinteger (x) to determine whether X is an integer

You can convert X to 10 to determine if it is equal to itself:

function Isinteger (x) {return 
 parseint (x, ten) = = x; 
}

ES6 expands the value and provides a static method Isinteger () to determine whether the parameter is an integer:

Number.isinteger//True
Number.isinteger (25.0)//True
Number.isinteger (25.1)//False
Number.isinteger ("M")//False
Number.isinteger (TRUE)//False

JavaScript can accurately represent an integer range between -2^53 and 2^53 (excluding two endpoints), exceeding this range and cannot accurately represent this value. ES6 introduces the Number.max_safe_integer and Number.min_safe_integer constants, which represent the upper and lower limits of this range, and provide Number.issafeinteger () To determine whether an integer is a safe integer.

10, in the following code, the number 1-4 in what order output? Why is this output?

(function () {
 console.log (1); 
 settimeout (function () {Console.log (2)}, 1000); 
 settimeout (function () {Console.log (3)}, 0); 
 Console.log (4);
}) ();

This is not much explained, mainly JavaScript timing mechanism and time cycle, do not forget that JavaScript is single-threaded. The detailed explanation can refer to the JavaScript operation mechanism from settimeout.

11, write a function of less than 80 characters, judge a string is not a palindrome string

function Ispalindrome (str) {
 str = str.replace (/\w/g, '). toLowerCase ();
 return (str = = Str.split ("). Reverse (). Join ("));

This problem I met on the Codewars, and included some good solution, you can poke here: palindrome for Your Dome

12. Write a sum method that works in the following ways

Console.log (sum (2,3)); Outputs 5
console.log (SUM (2) (3));//Outputs 5

For this problem, you can determine the number of parameters to achieve:

function sum () {
 var fir = arguments[0];
 if (arguments.length = = 2) {return
 arguments[0] + arguments[1]
 } else {return
 function (sec) {
 Return fir + sec;
 }}}
 

13, according to the following code fragment answer the question behind

for (var i = 0; i < 5; i++) {
 var btn = document.createelement (' button ');
 Btn.appendchild (document.createTextNode (' Button ' + i));
 Btn.addeventlistener (' click ', Function () {console.log (i);});
 Document.body.appendChild (BTN);
}

1, click Button 4, what will output in the console?

2, give a way to meet the expected implementation

    • 1, click on any of the 5 buttons, are output 5
    • 2, reference Iife.

14, what will the following code output? Why?

var arr1 = "John". Split ('); J o H n
var arr2 = Arr1.reverse (); n h o j
var arr3 = "Jones". Split ("); J o N e s
arr2.push (ARR3);
Console.log ("array 1:length=" + arr1.length + "last=" + arr1.slice ( -1));
Console.log ("array 2:length=" + arr2.length + "last=" + arr2.slice (-1));

What will it output? You run down to know that it may be unexpected in your.

Reverse () changes the array itself and returns a reference to the original array.

Slice usage Please refer to: Slice

15, what will the following code output? Why?

Console.log (1 + "2" + "2");
Console.log (1 + + "2" + "2");
Console.log (1 +-"1" + "2");
Console.log (+ "1" + "1" + "2");
Console.log ("A"-"B" + "2");
Console.log ("A"-"B" + 2);

Output what, run it yourself, you need to pay attention to three points:

When multiple numeric and numeric strings are mixed, it is related to the position of the operand

Console.log (2 + 1 + ' 3 '); //' Console.log '
(' 3 ' + 2 + 1);//' 321 '

A numeric string is converted to a number before it has a positive sign (-+ +) in the number

Console.log (typeof ' 3 '); String
console.log (typeof + ' 3 ');//number

Similarly, you can add a number to a string before the number.

Console.log (typeof 3); Number
Console.log (typeof (' +3));//string

For the result of an operation that cannot be converted to a number, it returns a NaN

Console.log (' a ' * ' SD '); Nan
console.log (' A '-' B ');//Nan

This graph is the rule of operation conversion

16,

If the list is large, the following recursive code can cause a stack overflow. What if the code is fixed without changing the recursive pattern?

var list = Readhugelist ();

var nextlistitem = function () {
 var item = List.pop ();

 if (item) {
 //Process the list item ...
 Nextlistitem ();
 }
;

The original solution is to add a timer:

var list = Readhugelist ();

var nextlistitem = function () {
 var item = List.pop ();

 if (item) {
 //Process the list item ...
 settimeout (Nextlistitem, 0);
 }
};

The principle of the solution, please refer to question 10th.

17, what is closure? Give an example to explain

can refer to this article: from the scope chain to talk about closure

18, what will the following code output? Why?

for (var i = 0; i < 5; i++) {
 settimeout (function () {console.log (i);}, I * 1000);
}

Please turn to the front, refer to question 4th, the solution is already on the top

19, explain the output of the following code

Console.log ("0 | | 1 = "+" (0 | | 1));
Console.log ("1 | | 2 = "+" (1 | | 2));
Console.log ("0 && 1 =" + (0 && 1));
Console.log ("1 && 2 =" + (1 && 2));

The logical and logical OR operator returns a value, both of which are short-circuit operators:

The number of operands that return the first false or the last that is true

Console.log (1 && 2 && 0); 0
console.log (1 && 0 && 1);//0
Console.log (1 && 2 && 3);//3

If an operand is false, the operand after that operand is not evaluated

The number of operands that are the first true or the last is false

Console.log (1 | | 2 | | 0); 1
console.log (0 | | 2 | | 1);//2
console.log (0 | | 0 | | false);//false

If an operand is true, the operands after that operand are not evaluated

If logical and logical or mixed operations, the logic and precedence are high:

Console.log (1 && 2 | | 0); 2
console.log (0 | | 2 && 1);//1
console.log (0 && 2 | | 1);//1

In JavaScript, the common false value:

0, ' 0 ', +0,-0, False, ', Null,undefined,null,nan
To note empty arrays ([]) and Empty objects ({}):

Console.log ([] = = False)//true
console.log ({} = = false)//false
Console.log (Boolean ([])//true
Console.log (Boolean ({}))//true

So in if, [] and {} All behave true:

20, explain the output of the following code

Console.log (false = = ' 0 ')
console.log (false = = ' 0 ')

Refer to the figure in the previous 14th operator conversion rule.

21, explain the output of the following code

var a={},
 b={key: ' B '},
 C={key: ' C '};

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

Console.log (A[b]);

The output is 456.

22, explain the output of the following code

Console.log (function f (n) {return ((n > 1)? n * F (n-1): N)}) (10));

The result is a factorial of 10. This is a recursive call, in order to simplify, I initialize the n=5, then the call chain and the return chain are as follows:

23, explain the output of the following code

(function (x) {return
 (function (y) {
 console.log (x);
 }) (2)
}) (1);

Output 1, a closure can access variables or parameters of an external scope.

24, explain the output of the following code, and fix the existing problems

var hero = {
 _name: ' John Doe ',
 getsecretidentity:function () {return
 this._name;
 }
};

var stolesecretidentity = hero.getsecretidentity;

Console.log (Stolesecretidentity ());
Console.log (Hero.getsecretidentity ());

Assigning getsecretidentity to stolesecretidentity is equivalent to defining the Stolesecretidentity function:

var stolesecretidentity = function () {return
 this._name;
}

The context is the global environment, so the first output undefined. To output John Doe, change the This point (hero) of the stolesecretidentity by means of call, apply, and bind.

The second is the method that invokes the object, outputting John Doe.

25, give you a DOM element, create a function that can access all child elements of the element, and pass each child element to the specified callback function.

function accepts two parameters:

    • DOM
    • The specified callback function

The original text uses depth first search (Depth-first-search) to give an implementation:

function Traverse (p_element,p_callback) {
 p_callback (p_element);
 var list = P_element.children;
 for (var i = 0; i < list.length i++) {
 Traverse (list[i],p_callback);//Recursive Call
 }
}

The above is for you to share 25 JavaScript interview questions, I hope to participate in the interview to help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.