10 geeks and secrets about JavaScript

Source: Internet
Author: User

Author: Andy Croxall
Link to the original article: Ten Oddities And Secrets About JavaScript
Translation Editor: Zhang xinxu

Data Types and definitions

1. Null is an object.
Among many JavaScript types, there is a Null type, which has a unique value of null, that is, its literal value, defined as a value that has no meaning at all. It looks like an object, and the following detection code:
Copy codeThe Code is as follows:
Alert (typeof null); // the 'object' is displayed'

As follows:

Although the typeof value is displayed as "object", null is not considered as an object instance. You must know that values in JavaScript are all Object instances. Each value is a Number Object, and each Object is an Object. Because null has no value, it is obvious that null is not an instance of anything. Therefore, the value below is equal to false.
Copy codeThe Code is as follows:
Alert (null instanceof Object); // false

Note: null is also interpreted as an object placeholder.

2. NaN is a numerical value.
NaN is intended to indicate that a value is not a numerical value, but it is a numerical value and is not equal to itself. It is strange to see the following code:
Copy codeThe Code is as follows:
Alert (typeof NaN); // The 'number' dialog box is displayed'
Alert (NaN = NaN); // false

The result is as follows:

Actually, NaN is not equal to anything. Make sure that only isNaN can be used for a certain item.
3. arrays without keywords are equivalent to false (about Truthy and Falsy)
The following is another of the best JavaScript geeks:
Copy codeThe Code is as follows:
Alert (new Array () = false); // true

The result is as follows:

To know what happened here, you need to understand the concept of truthy and falsy. They are a true/flase literal. In JavaScript, all non-Boolean values will have a built-in boolean flag. When this value is required to have a boolean behavior, this built-in Boolean value will appear, for example, if you want to compare it with a Boolean value.

Because Apple cannot be compared with pear, when JavaScript requires two different types of values to be compared, it will first weaken it to the same type. False, undefined, null, 0, "", NaN are all weakened to false. This type of forced conversion does not always exist, only when used as an expression. Let's look at the following simple example:
Copy codeThe Code is as follows:
Var someVar = 0;
Alert (someVar = false); // display true

The result is as follows:

In the above test, we tried to compare the values 0 and boolean values false. Because the data types of the two are incompatible, JavaScript will automatically convert them to the same truthy and falsy, 0 is equivalent to false (as mentioned above ).

You may have noticed that there are no empty arrays in the values equal to false above. The empty array is a strange trick: it actually belongs to truthy, but when the empty array is compared with the Boolean type, its behavior is falsy. Why? This is the reason. First, let's take an example to verify the strange temper of the empty array:
Copy codeThe Code is as follows:
Var someVar = []; // empty array
Alert (someVar = false); // The result is true.
If (someVar) alert ('hello'); // execute the alert statement, so someVar is treated as true.

The result is as follows:

Note: According to the author, the array has a built-in toString () method. For example, when alert is used directly, a string is popped up in the form of join, an empty array is a null string, which is equivalent to false. For more information, see the author's article Twisted logic: understanding truthy & falsy. However, I am surprised that, for example, null objects and empty functions, false is displayed when weak values are true or false. Why? Is it really because the array is a freak that requires special consideration?

To avoid the comparison problem of forced conversion, you can use strong equals (=) instead of weak equals (= ).
Copy codeThe Code is as follows:
Var someVar = 0;
Alert (someVar = false); // The result is true-0 and belongs to falsy.
Alert (someVar = false); // The result is false.-zero is a value, not a Boolean value.

The result is as follows (win7 FF4 ):

If you want to explore some of the special characteristics of forced type conversion in JavaScript, refer to the official documentation specifications:
Section 11.9.3 the ECMA-262
Regular Expression
4. replace () can accept callback Functions
This is one of the least-known secrets of JavaScript. It was first introduced in v1.3. In most cases, the use of replace () is similar to the following:
Copy codeThe Code is as follows:
Alert ('10 13 21 48 52 '. replace (// \ d +/g,' * '); // replace all numbers *

This is a simple replacement, a string, and an asterisk. However, what should we do if we want to have more control when the replacement happens? We only want to replace the value below 30. What should we do? At this time, if you only rely on regular expressions, it will be too much. We need to use the Dongfeng of the callback function to process each matching.
Copy codeThe Code is as follows:
Alert ('10 13 21 48 52 '. replace (/\ d +/g, function (match ){
Return parseInt (match) <30? '*': Match;
}));

When each matching is complete, the JavaScript Application callback function transmits the Matching content to the match parameter. Then, according to the filter rules in the callback function, either the asterisk is returned or the matching itself is returned (no replacement occurs ).

As follows:

5. Regular Expression: not only match and replace
Many javascript engineers only deal with regular expressions through match and replace. However, the regular expression-related methods defined by JavaScript are far more than these two.

It is worth mentioning that test () works in a similar way to match (), but the return value is different: test () returns a boolean type to verify whether a match exists, the execution speed is higher than match ().
Copy codeThe Code is as follows:
Alert (// \ w {3,}/. test ('hello'); // 'true' is displayed'

The code above is used to verify whether the string contains more than three common characters. Obviously, "hello" is compliant, so true is displayed.
The result is as follows:

We should also pay attention to the RegExp object. You can use this to create a dynamic Regular Expression object, for example:

Copy codeThe Code is as follows:
Function findWord (word, string ){
Var instancesOfWord = string. match (new RegExp ('\ B' + word + '\ B', 'ig '));
Alert (instancesOfWord );
}
FindWord ('car', 'Carl went to buy a car but had forgotten his credit card .');

Here, we dynamically create a match Verification Based on the parameter word. The purpose of this test code is to select the word car without differentiating the size. The eyes swept away and only one word in the test English sentence was car. Therefore, only one word is displayed here. \ B indicates the word boundary.

The result is as follows:

Functions and scopes
6. You can impersonate a scope.
Scope is used to determine what variables are available. Independent JavaScript (for example, JavaScript is not in the running Letter Number) operates under the global scope of the window object, window objects can be accessed in any situation. However, the local variables declared in the function can only be used in this function.
Copy codeThe Code is as follows:
Var animal = 'Dog ';
Function getAnimal (adjective) {alert (adjective + ''+ this. animal );}
GetAnimal ('lovely'); // The 'lovely dog' dialog box appears'

Here our variables and functions are declared in the global scope. This indicates the current scope. In this example, window is used. Therefore, this function looks for window. animal, that is, 'Dog. So far, everything is normal. However, in fact, we can let the function run in different scopes, ignoring its own scope. We can use a built-in call () method to impersonate a scope.
Copy codeThe Code is as follows:
Var animal = 'Dog ';
Function getAnimal (adjective) {alert (adjective + ''+ this. animal );};
Var myObj = {animal: 'camel '};
GetAnimal. call (myObj, 'lovely'); // The 'lovely camel' dialog box appears'

The first parameter in the call () method can impersonate this in the function. Therefore, this. animal here is actually myObj. animal, that is, 'camel. The following parameters are passed to the function body as common parameters.

Another related method is the apply () method, which acts on call (). The difference is that the parameters passed to the function are represented in arrays rather than independent variables. Therefore, if the above test code is represented by apply:
Copy codeThe Code is as follows:
GetAnimal. apply (myObj, ['lovely']); // function parameters are sent as Arrays

On the demo page, click the first button and the result is as follows:

The result of clicking the second and third buttons is as follows:
7. The function can execute itself.
Below is a very OK:
Copy codeThe Code is as follows:
(Function () {alert ('hello') ;}) (); // The 'hello' dialog box appears'

The parsing here is simple enough: declare a function, and then execute it immediately because () parsing. You may wonder why you want to do this (which is called directly after your ass). This seems a bit self-contradictory: The function usually contains the code we want to execute later, instead of executing the current parsing, we do not need to put the code in the function.

Another good use of self-executing functions (SEFs) is to bind variable values to delayed code, such as Event callback ), timeouts and intervals ). Example:
Copy codeThe Code is as follows:
Var someVar = 'hello ';
SetTimeout (function () {alert (someVar) ;},1000 );
Var someVar = 'Goodbye ';

Newbies always asks in the Forum why the timeout pop-up is goodbye instead of hello? The answer is that the callback function in timeout does not assign the value of the someVar variable until it is running. At that time, someVar had been rewritten by goodbye for a long time.

SEFs provides a solution to this problem. Instead of implicitly specifying the timeout callback as above, it directly transmits the someVar value as a parameter. The effect is remarkable, which means we have passed in and isolated the someVar value to protect it from changing whether it is followed by a earthquake, a tsunami, or a girlfriend's roar.
Copy codeThe Code is as follows:
Var someVar = 'hello ';
SetTimeout (function (someVar ){
Returnfunction () {alert (someVar );}
) (SomeVar), 1000 );
Var someVar = 'Goodbye ';

The wind and water flow, this time, the pop-up here is hello. This is the difference between function parameters and external variables.
For example, the last button is displayed as follows:
Browser
8. FireFox reads and returns colors in RGB format instead of Hex
Till now, I have not really understood why Mozilla is like this. For a clear understanding, let's look at the following example:
Copy codeThe Code is as follows:
<! --
# SomePara {color: # f90 ;}
-->
<P id = "somePara"> Hello, world! </P>
<Script>
Var ie = navigator. appVersion. indexOf ('msie ')! =-1;
Var p = document. getElementById ('somepara ');
Alert (ie? P. currentStyle. color: getComputedStyle (p, null). color );
</Script>

In most browsers, the pop-up result is ff9900, while in FireFox, the result is in rgb (255,153, 0) format. Often, when processing colors, we need to spend a lot of code to Convert RGB colors to Hex.
The following is the result of the above Code in different browsers:
Miscellaneous
0.1 + 0.2! = 0.3
This odd problem occurs not only in JavaScript, but also in computer science and affects many languages. The output result of the title equality is 0.30000000000000004.

This is a problem called machine precision. When JavaScript tries to execute this line of code (0.1 + 0.2), it converts the value to their preferred binary taste. This is the origin of the problem. 0.1 is actually not 0.1, but its binary form. In essence, when you write these values, they are doomed to lose precision. You may just want to get a simple two-digit decimal number, But what you get (according to the Chris Pine annotation) is a binary floating point computation. For example, if you want to translate a paragraph into simplified Chinese, but the result is traditional Chinese, there are still differences.

Generally, there are two ways to deal with this problem:

Convert it to an integer before calculation. After calculation, convert it to the expected decimal content.
Adjust your logic and set the allowed range to not specify the result.
For example, we should not do the following:
Copy codeThe Code is as follows:
Var num1 = 0.1, num2 = 0.2, shouldEqual = 0.3;
Alert (num1 + num2 = shouldEqual); // false

You can try it like this:
Copy codeThe Code is as follows:
Alert (num1 + num2> shouldEqual-0.001 & num1 + num2 <shouldEqual + 0.001); // true

10. undefined can be defined (defined)
We end with a little strange breeze. It may sound strange that undefined is not a reserved word in JavaScript, although it has a special meaning and is the only way to determine whether the variable is undefined. Therefore:
Copy codeThe Code is as follows:
Var someVar;
Alert (someVar = undefined); // display true

So far, everything seems calm and normal, but the plot is always so bloody:
Copy codeThe Code is as follows:
Undefined = "I'm not undefined! ";
Var someVar;
Alert (someVar = undefined); // display false!

This is why the most external closure functions in jQuery source code should have an undefined parameter that is not passed in, so as to prevent undefined from being compromised by some external operators.

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.