Analysis of 44 Javascript perversion

Source: Internet
Author: User
Tags pow

Original title from: http://javascript-puzzlers.herokuapp.com/

Readers can begin to feel. The original result of the author is 21/44 ...

The first time I did this set of questions not only doubt IQ, even life began to doubt ....

However, understanding the basics is a prerequisite for in-depth programming. Let's take a look at these abnormal problems in the end the metamorphosis is not abnormal!

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);p arseint (' 2 ', 1);p arseint (' 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 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      "

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.

The callback function accepts four parameters previousvalue, CurrentValue, Currentindex, array

It is important to note that the If the array is empty and no initialvalue were provided, TypeError would be thrown.

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

Answer an 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, + priority is greater than?

So the original question is equivalent to ' Value is true '? ' somthing ': ' nonthing ' 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, +), 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) {//NOTE here!!!        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   = 0.2var One   = 0.1var eight = 0.8var six   = 0.6[two-one = = one, Eight-six = = one)
    • 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, ' + ',-9, Infinity];values.map (Issane);

A point of knowledge

    • Arithmetic_operators#remainder

This problem is equivalent to

7% 2 =% 2 = 0 ' Total 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, Answer 3, NaN, 3

Question 13th
Array.isarray (Array.prototype)

A point of knowledge:

    • Array/prototype

A little-known 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 source of all evil, see

The answer is false.

Question 16th
' 5 ' + 3 ' 5 '-3

Two points of knowledge:

    • Arithmetic_operators#addition
    • Arithmetic_operators#subtraction

+ is used to represent two numbers and or string concatenation, which represents the difference between two numbers.

See examples to understand the difference:

> ' 5 ' + 3 ' + ' > 5 + ' 3 ' ' + ' > 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 is 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) + = + (f) = -1E = + (g) + -1f =-(G.) => ; -1G = + 1 +   1

So answer 2

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", UNDEFINEDX2]

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 was 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 =  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 the arguments object is an Array-like object corresponding to the arguments passed to a function.

That is to say arguments is an object, C is arguments[2], so the modification of C is to arguments[2].

So the answer is 21.

However!!!!!!

When the function parameter involves any rest parameters, the arguments is not a mapped argume when any default parameters or any destructured parameters. Nts object .....

Please see:

function sideffecting (ary) {  ary[0] = ary[2];} function Bar (a,b,c=3) {  c =  sideffecting (arguments);  Return a + B + C;} Bar (1,1,1)

The answer is!!!!

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 refer ence to the array.

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

The answer is window.

Question 22nd
Number.min_value > 0

True

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

This question is also possible.

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

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 true, as to why .....

Both objects get converted to strings and in both cases the resulting string is "2" I'm not convinced ...

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

It's a funny question, I did the right thing:) The answer is error, ' 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, 1,. 1 are legal numbers. So this is when we parse 3.toString. Does it belong to this number or function call? Only numbers, because 3. Legal!

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

The answer is 1, error.

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

Question 27th
var a =/123/,    b =/123/;a = = BA = = = B

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

The answer is false, 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

The answer is false, 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.

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

The answer is false, 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

Answer False

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)//  ?

First say the following answer ' F ', ' Empty ', ' function ', the answer to the error is not important ....

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

The second small asked the author in their own browser test is ", the fourth question is ' undefined '

So it should be platform-related. Here understand the parent = = = Function.prototype just fine.

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 ' is naturally all lowercase.

Answer: TRUE, True

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

[,,,] = [UNDEFINEDX3]

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 in length 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 is 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, quote 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 that is still Invalid date.

Answer Invalid Date

Question 38th
var a = function.length,    b = new Function (). Lengtha = = = B

We know that the length property of a function instance is the number of parameters for the signature of the functions, so b.length = = 0.

Another function.length is defined as 1 ...

So not equal .... Answer False

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.

The answer is false, False, False

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

Knowledge Points:

    • Math/min
    • Math/max

Interestingly, the Math.min parameter returns Infinity, Math.max does not pass parameter return-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 accepts a regular, if not, conversions according to New REGEXP (obj). So. and will not escape
Then/gif matched 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 var A; var a = ' bye ' is actually A; A = ' bye '

So the answer ' hello ', ' bye '

It's all over!

Summarize

Because the author level is limited, if the explanation is wrong, still 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 books should always look at AH??

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

Analysis of 44 Javascript perversion

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.