JavaScript you have to know the face question

Source: Internet
Author: User
Tags object object variable scope

1, Use typeof bar = = = "object" to judge bar is not an object of the potential disadvantages of God horse? How to avoid this kind of malpractice?

The disadvantage of using typeof is obvious (this disadvantage is the same as using instanceof):

let obj = {};let arr = [];console.log(typeof obj === ‘object‘);  //trueconsole.log(typeof arr === ‘object‘);  //trueconsole.log(typeof null === ‘object‘);  //true

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

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 = =:
Cherish life

and [] = = = False is the return False.

2. The following code will output God horse in the console? 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); //3console,log(typeof a); //undefined

Disassemble the variable assignment in the 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 output God horse in the console? 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 output is not difficult to judge, before ES6, JavaScript only function scope, so the Iife in Func has its own independent scope, and it can access to the external scope of self, so the third output will be an error, because this is within the scope of access to the U ndefined, the fourth output is bar. If you know closures, it's also easy to solve:

(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 poke this: talk about closures from a scope chain

4. Include JavaScript code in a function block what does God mean? Why do you do this?

In other words, why use immediate execution of function expressions (immediately-invoked functions expression).

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

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

The above output is not what you think of the 0,1,2,3,4, 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)}

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

(function($) {         //代码 } )(jQuery);
5, in strict mode (' use strict ') for JavaScript development God horse benefits?

Eliminate some unreasonable and unreasonable JavaScript grammar, reduce some strange behavior;
To eliminate some of the unsafe code operation, to ensure the security of code operation;
Improve compiler efficiency, increase running speed;
Pave the future for new versions of Javascript.

6. is the return value of the following two functions the same? Why?
function foo1(){  return {      bar: "hello"  };}function foo2(){  return  {      bar: "hello"  };}

In programming languages, it is essential to separate statements by using semicolons (;), which can increase the readability and cleanliness of your code. In js, if the statements are separate lines, it is usually possible to omit the semicolon (;) between the statements, and the JS parser will determine whether to automatically fill in the full number according to the normal compilation:

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

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

function foo2(){  return;  {      bar: "hello"  };}

So the second function is to return a Undefined.

7, God Horse is NaN, its type is God horse? How do I test if a value equals NaN?

Nan is the abbreviation for not a number, a special numeric value of JavaScript whose type is #, which can be determined by IsNaN (param) whether a value is NaN:

console.log(isNaN(NaN)); //trueconsole.log(isNaN(23)); //falseconsole.log(isNaN(‘ds‘)); //trueconsole.log(isNaN(‘32131sdasd‘)); //trueconsole.log(NaN === NaN); //falseconsole.log(NaN === undefined); //falseconsole.log(undefined === undefined); //falseconsole.log(typeof NaN); //numberconsole.log(Object.prototype.toString.call(NaN)); //[object Number]

In ES6, IsNaN () becomes the static method of Number: Number.isnan ().

8, explain the output of the following code
console.log(0.1 + 0.2);   //0.30000000000000004console.log(0.1 + 0.2 == 0.3);  //false

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

Because of the use of binary, JavaScript can not be limited to 1/10, 1/2 and so on such scores. 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 such as 0.1 + 0.2, the operand is first converted to binary and then calculated:

0.1 => 0.0001 1001 1001 1001…(无限循环)0.2 => 0.0011 0011 0011 0011…(无限循环)

The decimal portion of a double-precision floating-point number supports up to 52 bits, so the two add up to a string of 0.0100110011001100110011001100110011001100 ... a binary number truncated because of the limit of the number of floating-point numbers, at this time, And then convert it to decimal, which is 0.30000000000000004.

There are two common ways to ensure the correctness of floating-point calculation:

first, Ascending and then power down:

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.3console.log(add(0.15,0.2256)); //0.3756

The second is to use the built-in toprecision () and toFixed () methods, Note the Method's return value String.

function add(x, y) {    return x.toPrecision() + y.toPrecision()}console.log(add(0.1,0.2));  //"0.10.2"
9. Implement function Isinteger (x) to determine if X is an integer

You can convert the X to 10, judging if it is equal to Itself:

function isInteger(x) {     return parseInt(x, 10) === x; }

ES6 extends the value, providing a static method Isinteger () to determine whether the parameter is an integer:

Number.isInteger(25) // trueNumber.isInteger(25.0) // trueNumber.isInteger(25.1) // falseNumber.isInteger("15") // falseNumber.isInteger(true) // false

JavaScript can accurately represent an integer range between -2^53 and 2^53 (with no two endpoints), exceeding this range, and cannot accurately represent this Value. ES6 introduces two constants, Number.max_safe_integer and number.min_safe_integer, to represent the upper and lower bounds of this range, and provides a number.issafeinteger () To determine if an integer is a safe integer.

10. In the following code, what sequence does the number 1-4 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 to explain, mainly JavaScript timing mechanism and time loop, do not forget that JavaScript is Single-threaded. The detailed explanation can refer to the JavaScript running mechanism from Settimeout.

11, write a function less than 80 characters, judge whether a string is a palindrome string
function isPalindrome(str) {    str = str.replace(/\W/g, ‘‘).toLowerCase();    return (str == str.split(‘‘).reverse().join(‘‘));}

This question I met on the codewars, and included some good solution, can poke here: palindrome for Your Dome

12. Write a sum method that will work correctly as called in the following way
console.log(sum(2,3));   // Outputs 5console.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. Answer the following questions according to the code snippet below
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 be output on the console?
2, give a way to meet the expected realization

Answer: 1, Click on any of the 5 buttons, are output 5
2, Reference Iife.

14. What does the following code output? Why?
var arr1 = "john".split(‘‘); j o h nvar arr2 = arr1.reverse(); n h o jvar arr3 = "jones".split(‘‘); j o n e sarr2.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 may be unexpected in Your.

The description for reverse () on the MDN is Jiangzi:

Description
The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a refer ence to the Array.

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

For slice usage please refer to: slice

15. What does 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);

What to output, to run it yourself, you need to pay attention to three points:

1, multiple numeric and numeric string mixed operations, with the position of the operand is related

console.log(2 + 1 + ‘3‘); / /‘33’console.log(‘3‘ + 2 + 1); //‘321‘

A numeric string is converted to a number when the sign (+/-) is present in the number

console.log(typeof ‘3‘);   // stringconsole.log(typeof +‘3‘);  //number

similarly, You can add a number before the number to a string.

2.

console.log(typeof 3);   // numberconsole.log(typeof (‘‘+3));  //string

If the result of the operation cannot be converted to a number, NaN is returned

console.log(‘a‘ * ‘sd‘);   //NaNconsole.log(‘A‘ - ‘B‘);  // NaN

This graph is the rule of the Operation Transformation.

3. Operator Conversions

16, If the list is large, the following recursive code will cause a stack overflow. What if the code is modified without changing the recursive mode?
var list = readHugeList();var nextListItem = function() {    var item = list.pop();    if (item) {        // process the list item...        nextListItem();    }};

The solution in the original is to add a timer:

var list = readHugeList();var nextListItem = function() {    var item = list.pop();    if (item) {        // process the list item...        setTimeout( nextListItem, 0);    }};

Please refer to question 10th for the principle of Solution.

17. What is a closure? Examples Show

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

18. What does 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 the 4th question, 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, and both are short-circuiting operators:

The logical and the operand that returns the first is False or the last is true

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

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

The logical or return operand of the first is true or the last is false

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

If an operand is true, then the operand after the operand is not evaluated

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

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

In JavaScript, the common false value is:

Be aware of empty arrays ([]) and empty objects ({}):

console.log([] == false) //trueconsole.log({} == false) //falseconsole.log(Boolean([])) //trueconsole.log(Boolean({})) //true

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

20, explain the output of the following code
console.log(false == ‘0‘)console.log(false === ‘0‘)

Please refer to the diagram of the operator conversion rule in question 14th Above.

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, refer to the original explanation:

The reason for this is as Follows:when setting a object property, JavaScript would implicitly stringify the parameter Val Ue. In this case, since B and C is both objects, they'll both be converted to "[object object]". As a result, a[b] anda[c] is both equivalent to A["[object Object]") and can be used Interchangeably. Therefore, setting or referencing a[c] is precisely the same as setting or referencing a[b].

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 n=5, then the call chain and the return chain are as Follows:

Recursive

23, explain the output of the following code
(function(x) {    return (function(y) {        console.log(x);    })(2)})(1);

Output 1, The closure can access variables or parameters outside the 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 of the stolesecretidentity is the global environment, so the first output is Undefined. To output John Doe, change the Stolesecretidentity's this point (hero) by means of call, apply, and Bind.

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

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

A 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   }}

JavaScript you have to know the face question

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.