Analysis of 44 Javascript perverts (up \ Down)

Source: Internet
Author: User
Tags pow

Question 1th
["1", "2", "3"].map(parseInt)

Knowledge Points:

    • Array/map
    • Number/parseint
    • JavaScript parseint

First, map accepts two parameters, a callback function callback, the This value of a callback function

Where the callback function accepts three parameters CurrentValue, index, arrary;

In the topic, map only passes in the callback function--parseint.

Second, parseint only accepts two two parameter string, radix (cardinality).

Optional. Represents the cardinality of the number to parse. The value is between 2 and 36.

If this argument is omitted or its value is 0, the number is parsed based on 10. If it starts with "0x" or "0X", it will have a base of 16.

If the parameter is less than 2 or greater than 36, parseint () returns NaN.

So the question is

parseInt(‘1‘, 0);parseInt(‘2‘, 1);parseInt(‘3‘, 2);

First, the latter two parameters are not valid.

So the answer is[1, NaN, NaN]

Question 2nd
[typeof null, null instanceof Object]

Two points of knowledge:

    • Operators/typeof
    • Operators/instanceof
    • Operators/instanceof (Medium)

typeof returns a String representing the type.

The instanceof operator is used to detect whether the Constructor.prototype exists on the prototype chain of the Parameter object.

This topic can be directly read the link ... Because typeof null === ‘object‘ from the beginning of the language is like this ....

See the following table for the results of typeof:

type         resultUndefined   "undefined"Null        "object"Boolean     "boolean"Number      "number"String      "string"Symbol      "symbol"Host object Implementation-dependentFunction    "function"Object      "object"

So the answer[object, false]

Question 3rd
[ [3,2,1].reduce(Math.pow), [].reduce(Math.pow) ]

Knowledge Points:

    • Array/reduce

arr.reduce(callback[, initialValue])

Reduce accepts two parameters, a callback, and an initial value.

A callback function accepts four parameterspreviousValue, currentValue, currentIndex, array

It is important to note thatIf the array is empty and no initialValue was provided, TypeError would be thrown.

So the second expression will report an exception. The first expression is equivalent to anMath.pow(3, 2) => 9; Math.pow(9, 1) =>9

Answeran error

Question 4th
var val = ‘smtg‘;console.log(‘Value is ‘ + (val === ‘smtg‘) ? ‘Something‘ : ‘Nothing‘);

Two points of knowledge:

    • Operators/operator_precedence
    • Operators/conditional_operator

+in short, the priority is greater than?

So the original question ‘Value is true‘ ? ‘Somthing‘ : ‘Nonthing‘ is equivalent instead of‘Value is‘ + (true ? ‘Something‘ : ‘Nonthing‘)

Answer‘Something‘

Question 5th
var name = ‘World!‘;(function () {    if (typeof name === ‘undefined‘) {        var name = ‘Jack‘;        console.log(‘Goodbye ‘ + name);    } else {        console.log(‘Hello ‘ + name);    }})();

This relatively simple, a knowledge point:

    • Hoisting

In JavaScript, functions and variables are promoted. Variable elevation is the behavior that JavaScript moves the declaration to the top of the scope scope (global domain or current function scope).

This topic is equivalent to

var name = ‘World!‘;(function () {    var name;    if (typeof name === ‘undefined‘) {        name = ‘Jack‘;        console.log(‘Goodbye ‘ + name);    } else {        console.log(‘Hello ‘ + name);    }})();

So the answer is‘Goodbye Jack‘

Question 6th
var END = Math.pow(2, 53);var START = END - 100;var count = 0;for (var i = START; i <= END; i++) {    count++;}console.log(count);

A point of knowledge:

    • Infinity

In JS, Math.pow (2, 53) = = 9007199254740992 is the maximum value that can be represented. The maximum value plus one or the maximum value. So the loop doesn't stop.

Question 7th
var ary = [0,1,2];ary[10] = 10;ary.filter(function(x) { return x === undefined;});

The answer is[]

Read an article Understanding sparse arrays

    • Sparse arrays and dense arrays in JavaScript
    • Array/filter

Let's take a look at Array.prototype.filter's Polyfill:

if (!Array.prototype.filter) {  Array.prototype.filter = function(fun/*, thisArg*/) {    ‘use strict‘;    if (this === void 0 || this === null) {      throw new TypeError();    }    var t = Object(this);    var len = t.length >>> 0;    if (typeof fun !== ‘function‘) {      throw new TypeError();    }    var res = [];    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;    for (var i = 0; i < len; i++) {      if (i in t) { // 注意这里!!!        var val = t[i];        if (fun.call(thisArg, val, i, t)) {          res.push(val);        }      }    }    return res;  };}

We see that when iterating over this array, we first check that the index value is not an attribute of the array, so let's test it.

0 in ary; => true3 in ary; => false10 in ary; => true

That is, since 3-9 are not initialized ' pits '!, these indexes do not exist with the array. These ' pits ' are skipped at the time of the function call of array.

Question 8th
var two   = 0.2var one   = 0.1var eight = 0.8var six   = 0.6[two - one == one, eight - six == two]
    • JavaScript design flaws? Floating-point arithmetic: 0.1 + 0.2! = 0.3

Floating-point numbers in the IEEE 754 standard do not accurately represent decimals

When is it accurate and when is it not? I do not know ...

Answer[true, false]

Question 9th
function showCase(value) {    switch(value) {    case ‘A‘:        console.log(‘Case A‘);        break;    case ‘B‘:        console.log(‘Case B‘);        break;    case undefined:        console.log(‘undefined‘);        break;    default:        console.log(‘Do not know!‘);    }}showCase(new String(‘A‘));

Two points of knowledge:

    • Statements/switch
    • String

switch is strictly compared, and string instances are not the same as strings.

var s_prim = ‘foo‘;var s_obj = new String(s_prim);console.log(typeof s_prim); // "string"console.log(typeof s_obj);  // "object"console.log(s_prim === s_obj); // false

The answer is‘Do not know!‘

Question 10th
function showCase2(value) {    switch(value) {    case ‘A‘:        console.log(‘Case A‘);        break;    case ‘B‘:        console.log(‘Case B‘);        break;    case undefined:        console.log(‘undefined‘);        break;    default:        console.log(‘Do not know!‘);    }}showCase2(String(‘A‘));

Explain:
String(x) does not create an object but does return a string, i.e. typeof String(1) === "string"

Or just the point of knowledge, but string is not only a constructor function called directly return a string oh.

Answer‘Case A‘

Question 11th
function isOdd(num) {    return num % 2 == 1;}function isEven(num) {    return num % 2 == 0;}function isSane(num) {    return isEven(num) || isOdd(num);}var values = [7, 4, ‘13‘, -9, Infinity];values.map(isSane);

A point of knowledge

    • Arithmetic_operators#remainder

This problem is equivalent to

7 % 2 => 14 % 2 => 0‘13‘ % 2 => 1-9 % % 2 => -1Infinity % 2 => NaN

It is important to note that the sign of the remainder varies with the first operand.

Answer[true, true, true, false, false]

Question 12th
parseInt(3, 8)parseInt(3, 2)parseInt(3, 0)

The first question has been told, the answer3, NaN, 3

Question 13th
Array.isArray( Array.prototype )

A point of knowledge:

    • Array/prototype

A little-known practical fact: Array.prototype => [] ;

Answer:true

Question 14th
var a = [0];if ([0]) {  console.log(a == true);} else {  console.log("wut");}
    • Javascript-equality-table

Answer:false

Question 15th
[]==[]

==is the root of all evil, see

The answer isfalse

Question 16th
‘5‘ + 3‘5‘ - 3

Two points of knowledge:

    • Arithmetic_operators#addition
    • Arithmetic_operators#subtraction

+Used to denote a two-digit sum or string concatenation, - representing a difference of two.

See examples to understand the difference:

> ‘5‘ + 3‘53‘> 5 + ‘3‘‘53‘> 5 - ‘3‘2> ‘5‘ - 32> ‘5‘ - ‘3‘2

That is to say - , as much as possible to the two operand into a number, and if the two + sides are not all numbers, then the string concatenation.

The answer is‘53‘, 2

Question 17th
1 + - + + + - + 1

This is supposed to be (upside down).

1 + (a)  => 2a = - (b) => 1b = + (c) => -1c = + (d) => -1d = + (e) => -1e = + (f) => -1f = - (g) => -1g = + 1   => 1

So the answer2

Question 18th
var ary = Array(3);ary[0]=2ary.map(function(elem) { return ‘1‘; });

Sparse array. With the 7th question.

The array in question is actually an array of length 3, but no content, and the operation on the array skips these uninitialized ' pits '.

So the answer is["1", undefined × 2]

This place is affixed with Array.prototype.map Polyfill.

Array.prototype.map = function(callback, thisArg) {        var T, A, k;        if (this == null) {            throw new TypeError(‘ this is null or not defined‘);        }        var O = Object(this);        var len = O.length >>> 0;        if (typeof callback !== ‘function‘) {            throw new TypeError(callback + ‘ is not a function‘);        }        if (arguments.length > 1) {            T = thisArg;        }        A = new Array(len);        k = 0;        while (k < len) {            var kValue, mappedValue;            if (k in O) {                kValue = O[k];                mappedValue = callback.call(T, kValue, k, O);                A[k] = mappedValue;            }            k++;        }        return A;    };
Question 19th
function sidEffecting(ary) {  ary[0] = ary[2];}function bar(a,b,c) {  c = 10  sidEffecting(arguments);  return a + b + c;}bar(1,1,1)

This is a big hole, especially when it comes to ES6 grammar.

Knowledge Points:

    • Functions/arguments

First of allThe arguments object is an Array-like object corresponding to the arguments passed to a function.

In other words arguments object , C is arguments[2], so the modification of C is the modification of arguments[2].

So the answer is 21 .

However!!!!!!

When the function parameter any rest parameters, any default parameters or any destructured parameters is involved, this arguments is not a ... mapped arguments object

Please see:

function sidEffecting(ary) {  ary[0] = ary[2];}function bar(a,b,c=3) {  c = 10  sidEffecting(arguments);  return a + b + c;}bar(1,1,1)

The answer is 12 !!!!

Please understand the reader carefully!!

Question 20th
var a = 111111111111111110000,    b = 1111;a + b;

The answer is still 111111111111111110000 . The explanation is Lack of precision for numbers in JavaScript affects both small and big numbers. but the author does not quite understand .... Please enlighten the reader!

Question 21st
var x = [].reverse;x();

This problem is interesting!

Knowledge Points:

    • Array/reverse

The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

That is, the caller (this) is returned at the end, but when X executes, the context is global. So the final return is window .

The answer iswindow

Question 22nd
Number.MIN_VALUE > 0

true

First here today, next time we look at the 22 questions!

Question 23rd
[1 < 2 < 3, 3 < 2 < 1]

This question is also possible.

This problem will make people think that is 2 > 1 && 2 < 3 actually not.

This problem is equivalent to

 1 < 2 => true; true < 3 =>  1 < 3 => true; 3 < 2 => false; false < 1 => 0 < 1 => true;

The answer is[true, true]

Question 24th
// the most classic wtf2 == [[[2]]]

I guessed the question. I guess, as for why ..... true

both objects get converted to strings and in both cases the resulting string is "2"I can't believe it.

Question 25th
3.toString()3..toString()3...toString()

It's a funny question, I did the right thing:) The answer iserror, ‘3‘, error

You'd be more puzzled if you changed the wording.

var a = 3;a.toString()

The answer is ‘3‘ ;

Why is it?

Because in JS 1.1 , it 1. is a .1 valid number. So when it comes to parsing, 3.toString . does this really belong to this number or function call? Only numbers, because it's 3. legal!

Question 26th
(function(){  var x = y = 1;})();console.log(y);console.log(x);

The answer is1, error

Y is assigned a global value. X is a local variable. So when I print X, I report it.ReferenceError

Question 27th
var a = /123/,    b = /123/;a == ba === b

Even if the literal literals are consistent, they are not equal.

Answerfalse, false

Question 28th
var a = [1, 2, 3],    b = [1, 2, 3],    c = [1, 2, 4]a ==  ba === ba >   ca <   c

Arrays of equal literals are also unequal.

Arrays are compared by dictionary order when comparing sizes

Answerfalse, false, false, true

Question 29th
var a = {}, b = Object.prototype;[a.prototype === b, Object.getPrototypeOf(a) === b]

Knowledge Points:

    • Object/getprototypeof

Only Function has a prototype attribute. So a.prototype for undefined .

And Object.getPrototypeOf(obj) returns a prototype of a specific object (the object's internal [[prototype]] value)

Answerfalse, true

Question 30th
function f() {}var a = f.prototype, b = Object.getPrototypeOf(f);a === b

F.prototype is the object that would become the parent of any objects created with new F while object.getprototypeof return s the parent in the inheritance hierarchy.

F.prototype is a prototype of an F instance created using new. And Object.getprototypeof is the prototype of the F function.

Please see:

a === Object.getPrototypeOf(new f()) // trueb === Function.prototype // true

Answerfalse

31
function foo() { }var oldName = foo.name;foo.name = "bar";[oldName, foo.name]

Answer[‘foo‘, ‘foo‘]

Knowledge Points:

    • Function/name

Because the name of the function is immutable.

Question 32nd
"1 2 3".replace(/\d/g, parseInt)

Knowledge Points:

    • String/replace#specifying_a_function_as_a_parameter

str.replace(regexp|substr, newSubStr|function)

If the second argument passed by the Replace function is a function, then the function will accept the following parameters

    • Match first is a matching string
    • P1, p2 .... Then a regular grouping.
    • Offset match matches the index
    • String Entire string

Since the regular in the topic is not grouped, it is equivalent to asking

parseInt(‘1‘, 0)parseInt(‘2‘, 2)parseInt(‘3‘, 4)

Answer:1, NaN, 3

Question 33rd
function f() {}var parent = Object.getPrototypeOf(f);f.name // ?parent.name // ?typeof eval(f.name) // ?typeof eval(parent.name) //  ?

It's not important to say the answer first ..... ‘f‘, ‘Empty‘, ‘function‘, error

The first and third small questions here are very simple and do not explain.

The second small asked the author in his own browser when the test is ‘‘ , the fourth question is‘undefined‘

So it should be platform-related. It's good to know here parent === Function.prototype .

Question 34th
var lowerCaseOnly =  /^[a-z]+$/;[lowerCaseOnly.test(null), lowerCaseOnly.test()]

Knowledge Points:

    • Regexp/test

Here the test function converts the argument to a string. ‘nul‘, ‘undefined‘ naturally all lowercase.

Answer:true, true

Question 35th
[,,,].join(", ")

[,,,] => [undefined × 3]

Because JavaScript allows the last element to be followed when the array is defined , , this is a sparse array of length three (which is three and not 0, 1, 23 properties, OH)

Answer:", , "

Question 36th
var a = {class: "Animal", name: ‘Fido‘};a.class

This question compares Rogue. Because it's browser-related, class it's a reserved word (now it's a keyword)

So the answer is not important, it is important that you try to avoid retaining words when taking property names. If used, enclose the quotation mark.a[‘class‘]

Question 37th
var a = new Date("epoch")

Knowledge Points:

    • Date
    • Date/parse

Simply put, if you call the constructor of Date to pass in a string, you need to conform to the specification, which satisfies the date.parse condition.

It is also important to note that if the format error constructor returns an instance of date Invalid Date .

AnswerInvalid Date

Question 38th
var a = Function.length,    b = new Function().lengtha === b

We know that the property of a length function instance is the number of arguments to the signature, so b.length = = 0.

Another function.length is defined as 1 ...

So not equal .... Answerfalse

Question 39th
var a = Date(0);var b = new Date(0);var c = new Date();[a === b, b === c, a === c]

Or a question about date, it's important to note that

    • If the parameter is not passed is equivalent to the current time.
    • Returns a string if it is a function call.

Answerfalse, false, false

Question 40th
var min = Math.min(), max = Math.max()min < max

Knowledge Points:

    • Math/min
    • Math/max

Interestingly, Math.min does not pass arguments back Infinity , Math.max does not pass arguments back -Infinity

Answer:false

Question 41st
function captureOne(re, str) {  var match = re.exec(str);  return match && match[1];}var numRe  = /num=(\d+)/ig,    wordRe = /word=(\w+)/i,    a1 = captureOne(numRe,  "num=1"),    a2 = captureOne(wordRe, "word=1"),    a3 = captureOne(numRe,  "NUM=2"),    a4 = captureOne(wordRe,  "WORD=2");[a1 === a2, a3 === a4]

Knowledge Points:

    • Regexp/exec

The popular Speaking

Because the first regular has a G option that will ' memorize ' what he matches, and so on, he will continue from the last matching index, and the second one will not

As an example,

var myRe = /ab*/g;var str = ‘abbcdefabh‘;var myArray;while ((myArray = myRe.exec(str)) !== null) {  var msg = ‘Found ‘ + myArray[0] + ‘. ‘;  msg += ‘Next match starts at ‘ + myRe.lastIndex;  console.log(msg);}// Found abb. Next match starts at 3// Found ab. Next match starts at 9

So a1 = ' 1 '; a2 = ' 1 '; a3 = null; a4 = ' 2 '

Answer[true, false]

Question 42nd
var a = new Date("2014-03-19"),    b = new Date(2014, 03, 19);[a.getDay() === b.getDay(), a.getMonth() === b.getMonth()]

This one....

JavaScript inherits years old design from C:days is 1-indexed in C's struct TM, but months is 0 indexed. In addition to, GetDay returns the 0-indexed day of the week, to get the 1-indexed day of the month has to use G Etdate, which doesn ' t return a Date object.

a.getDay()3b.getDay()6a.getMonth()2b.getMonth()3

It's all a routine!

Answer[false, false]

Question 43rd
if (‘http://giftwrapped.com/picture.jpg‘.match(‘.gif‘)) {  ‘a gif file‘} else {  ‘not a gif file‘}

Knowledge Points:

    • String/match

String.prototype.match accept a regular, if not, follow the new RegExp(obj) conversions. So it . won't escape.
Then /gif it matches the/.gif/.

Answer:‘a gif file‘

Question 44th
function foo(a) {    var a;    return a;}function bar(a) {    var a = ‘bye‘;    return a;}[foo(‘hello‘), bar(‘hello‘)]

In two functions, a as a parameter is actually declared, so it var a; var a = ‘bye‘ is actuallya; a =‘bye‘

So the answer‘hello‘, ‘bye‘

It's all over!

Summarize

Due to the author's limited level, if the explanation is wrong, also hope to point out

Through the collation, the author found that most of the topics are because of their basic knowledge or the parameters of an API to understand deviations to do wrong.

The author of the hardest hit in the prototype that piece, so this time is abused and finishing still very meaningful ah.

I believe that solid foundation is the premise of in-depth programming. So the basic book should always be read.

At the end of the puzzle, now look at the sick.

Analysis of 44 Javascript perverts (up \ Down)

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.