A line of magical JavaScript code

Source: Internet
Author: User
Tags bitwise object object

A line of magical JavaScript code

A line of Magic JS Code, is in a blog park inside see, then I was shocked, this is not the legendary ZB magic ... Haha (decisively reproduced over). The reason for writing an article is that before the group of Ink dust sent a section of JS code, as follows:
(! (~+[])+{})[--[~+""][+[]]*[~+[]] + ~~!+[]]+({}+[])[[~!+[]]*~+[]]
Then let everyone run, out of the results let people a bit unexpected, please see: too coquettish has wood! If someone denigrate the front-end despise JS, then you can send this code to him ~ but then again, what is the principle of this?  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 string, step 2 is swapped with 3, if Preferredtype not, the date instance is set to string, the others are number 2. Convert the value to number by Tonumber () and look directly at the table of ECMA 9.3 http://es5.github.io/#x9.3 The rules are as follows:
Parameters Results
Undefined NaN
Null +0
Boolean True is converted to 1,false to +0
Number No conversion required
String Parsed by a string into a number. 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:
Parameters Results
Undefined "Undefined"
Null "NULL"
Boolean "True" or "false"
Number Number as a string. For example, "1.765″
String No conversion required
  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 ~ First Look at the simplest subexpression 16:+[] only one operand [], must be converted to number, according to the rules above 2,[] is the array, object type, that is, object. 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 of the ValueOf method, the array call valueof will return itself, as follows: This time, we get an empty string "", has not finished, see the above Rule 2 description, continue to call Tonumber, converted to number type, as follows: Done! Sub-expression 16 conversion complete, +[], and finally get 0.   See sub-expression 15:[~+ ""] empty string "" preceded by two unary operators, but the operand is only one, so the final type to be converted 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. Do not forget, this sub-expression is also wrapped in brackets outside, so the final value is [-1], that is, an array, there is only one element -1.  next look at the sub-expression 13 is simple, the 15, 16 to fill in, it becomes this: –[-1][0], take the No. 0 element of the array,  Then the self-subtraction, the result is-2, is not so easy! Continue to go up, sub-expression 14: [~+[]] In fact, the principle of 15, and 16 is very obvious, the answer [1] continue to seek subexpression 9, at the moment it has become: -2*[-1], there is a little different, but it doesn't matter, we still follow the rules, operators are multiplication sign *, of course, do mathematical operations , then the [-1] will have to be converted to number, similar to the 16 method, the process is as follows: ① call toprimitive, found to be the object type ② call valueof, return itself [ -1]③ because it is not the original type, continue to call ToString, return " -1″④ " -1″ is the original type, then call Tonumber, return -1⑤ with 2, return 2 sub-expression 10:~~!+[], say no more, 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 rootAccording 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, the {} should first be converted to the original type, the process is as follows: ① call toprimitive, found to be the object type ② call valueof, return itself {},③ is not the original type, call ToString, Return "[Object object ] "④false and" [Object Object] "added, false first converted to the string" false "⑤ The result" False[object object "" know the expression 3 and 4, we can see the expression 1, at this time it is this: " False[object Object] "[3], because this [] can take the substring of the string, 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, let 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, 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?

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.