A line of magical JavaScript code

Source: Internet
Author: User
Tags bitwise object object

the reason for writing an article is that before a group of friends sent a section of JS code, as follows:(! ( ~+[])+{})[--[~+""][+[]]*[~+[]] + ~~!+[]]+({}+[])[[~!+[]]*~+[]]then let everyone run, out of the results of a bit unexpected, see:  It's too much of a wood! If someone denigrate the front-end despise JS, then you can send this code to him ~but then again, what is this principle? Why does a bunch of symbolic operations result in two characters, and it happens to be a sb! In fact, by the type of JS conversion of some basic principles, this article to reveal how "SB" is refined. I believe that if you can make this clear, and then encounter the type of conversion and other topics, you can instantly kill.  the first thing to apply to the first knowledge is the priority of the JS operator, because such a long operation to see the people blurred, we have to first according to priority divided into n small segments, and then conquer. The precedence is arranged in the following table:priority from high to Low:
Operator

Description

. [ ] ( )

field access, array index, function call, and expression grouping

++ -- - ~ ! Delete new typeof void

Unary operators, return data types, object creation, undefined values

* / %

Multiply, divide, and find the remainder

+ - +

Add, subtract, string concatenation

<< >> >>>

Shift

< <= > >= instanceof

Less than, less than or equal to, greater than, greater than or equal to, or not an instance of a particular class

== != === !==

Equality, inequality, equality, not congruent

&

Bitwise "and"

^

Bitwise XOR

|

Bitwise "OR"

&&

Logical "and"

||

Logical "or"

?:

Conditional operations

= OP=

Assignment, assignment operations (e.g. + = and &=)

,

Multiple calculations

According to this rule, we divide this string operation into the following 16 sub-expressions:

  operator is marked in red, one thing may not be aware of, in fact, the brackets [] is also an operator, used to access the array of items through the index, in addition to access the string of sub-characters, a bit similar to the Charat method, such as: ' ABCD ' [1]//return ' B '. And the precedence of the brackets is the highest.   The end of preprocessing, the next thing to use is the type of JavaScript conversion knowledge. Let's start by talking about the type of conversions that need to be made. Type conversions are required when the operand types on either side of the operator are inconsistent or are not basic (also called primitive types). The class is divided by the operator first:
    • Minus-, multiplication sign *, must be a mathematical operation, so the operand needs to be converted to number type.
    • Plus +, may be string concatenation, or mathematical operations, so it may be converted to number or string
    • Unary operations, such as +[], with only one operand, converted to number type
Here's a look at the conversion rules.
1. For non-primitive types , convert the value to the original type by Toprimitive (): toprimitive (input, preferredtype?) the optional parameter preferredtype is number or string. The return value is any original value. If Preferredtype is number, the order of execution is as follows: (reference: http://es5.github.io/#x9.1) if input is primitive, return Otherwise, input is object. Call Obj.valueof (). If the result is primitive, return. Otherwise, call obj.tostring (). If the result is primitive, return Otherwise, throw TypeError if Preferredtype is a string, step 2 is swapped with 3, and if Preferredtype is not, the date instance is set to string, and the others are number
2. Convert the value to number by Tonumber () and look directly at the http://es5.github.io/table of the ECMA 9.3 #x9.3The rules are as follows:
parameter result
undefined nan
null +0
boolean true converted to 1,false to +0
number No need to convert
string The string is parsed into numbers. For example, "324" is converted to 324

  3. Convert the value to a string by ToString () and look directly at the table of ECMA 9.8 http://es5.github.io/#x9.8

The rules are as follows:
parameter result
undefined "undefined"
null "null"
boolean
number number as a string. For example, "1.765"
string No need to convert
The rule is so much, then practice, according to the sub-expression we have divided, step-by-step to the magic code to execute out. Start ~    See the simplest sub-expression first 16:+[]  there is only one operand [], which must be converted to number, according to the above rule 2,[] is the array, the object type, that is, objects. So you have to call toprimitive to the original type, and Preferredtype is number, and this parameter represents a more "inclined" type of conversion, which is definitely number. Then first call the array's valueof method, and the array call valueof returns itself, as follows:   this time, we get an empty string "", not yet finished, look at the above Rule 2 description, continue to call Tonumber, converted to number type, as follows:    It's done ! Sub-expression 16 conversion complete, +[], and finally get 0.  See sub-expression 15:[~+ ""]The empty string "" is preceded by two unary operators, but there is only one operand, so the final type to convert to is number. See Rule 2, empty string call Tonumber get 0. Next is ~, what is this? It is a bitwise operator, which can be recorded as negative and then minus one, so ~0 is-1. don't forget, this subexpression is enclosed with brackets, so the final value is [-1], which is an array with only one element -1. next look at the sub-expression 13 is simple, put 15, 16 to fill in, it becomes this:--[-1][0], take the No. 0 element of the array, and then self-subtraction, the result is-2, is not so easy! continue to go up, sub-expression: [~+[]]In fact, the principle of 15, and 16 is very obvious, the answer [-1] continue to find the subexpression 9, now it has become: -2*[-1], there is a little different, but it doesn't matter, we still follow the rules, the operator is multiplication sign *, of course, do mathematical operations, then the [-1] will have to be converted to number, and 16 of the method is similar, the process is as follows:① called toprimitive and found to be object type② calls valueof, returns itself [-1]③ continue calling ToString because it is not the original type, return "-1"④ "-1" is the original type, then call Tonumber, return-1⑤ is multiplied by 2 and returns 2 sub-expression 10:~~!+[], no more said, answer 1. is a unary calculation from right to left.  with 9 and 10, we came to subexpression 4, and now it's been like this: 2+1, well, I don't say much.  continue to look at the expression 7:! (~+[]), ~+[]=-1, this according to the above already know, that!-1 is what? Here to say this exclamation point, it is the meaning of logic, it will convert the expression into a Boolean type, the conversion rules and JS Truthy and Falsy principle is the same, followed by the number, except 0 is false, followed by the string, except the empty string is false. The!-1 here is, of course, false.  the next expression 3:false+{} is a bit critical. A spask an object, then this {} should first be converted to the original type, the process is as follows:① called toprimitive and found to be object type② calls valueof, returns itself {},③ is not the original type, call ToString and Return "[Object Object]"④false Add to "[Object Object]", false first to string "false"⑤ added result "False[object object " knowing the expressions 3 and 4, we can look at expression 1, at this point it is this: "False[object object" [3], because this [] can take a string of sub-characters, like Charat, so get the result "s" after the difficult process above, we got the character "s", that is, the left half of the picture, the rest of the "B", the same principle can be made out, I do not show you here, leave you practice it ~     Review This process is not complex, but there are some need to repeat the work, as long as you have mastered the priority of the operation, can be broken into a small string of large strings, and then the use of the knowledge of the type conversion to deal with it. How do you think it's magical to see this place? If someone despise JS, please send this code to him, if he wants to know the answer, please send this article to him ~

A line of magical JavaScript code

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.