Large collection of traps in JavaScript (1)

Source: Internet
Author: User
Tags add numbers

This article mainly introduces the weird Javascript, without a doubt, it definitely has a strange side. When software developers start to write code in the world's most widely used language, they will find many interesting "Features" in this process ". Even sophisticated Javascript developers can find some interesting new traps in this article. Pay attention to these traps and enjoy the "fun" brought by these traps "!

Functions and operators

Equal sign

= When the operator is compared, the type is forcibly converted, which means that it can compare two objects of different types, before performing the comparison, it will try to convert the two objects into the same type. For example:

 
 
  1. "1" == 1 //true 

However, this will often mislead us, and we do not need to compare it like this. In the above example, we can convert the string to a numeric type, and then compare it with the type-sensitive triple equal sign (=), for example:

 
 
  1. Number("1") === 1; //true 

Or, better, make sure that the type of the operand you put in the first place is correct.

Because the dual-equal sign has forced type conversion, it will break the general transfer rule, which is a little scary. Please refer to the following column:

 
 
  1. "" = 0 // true-a null string is forcibly converted to a number 0.
  2. 0 = "0" // true-the number 0 is forcibly converted to the string "0"
  3. "" = "0" // false-both operands are strings, so no forced conversion is performed.

If the triple equal sign is used, false is returned for all the above three comparisons.

ParseInt does not use 10 as the digit base.

If you ignore the second parameter of parseInt, the base number is determined by the following rules:

◆ The default base is 10, which is parsed in decimal format.

◆ If the number starts with 0x, the base number is 16, which is parsed in hexadecimal notation.

◆ If the number starts with 0, the base number is 8, which is parsed in octal format.

A common error is that we ask the user to enter a number starting with 0. At this time, it is parsed in octal format, so we can see the following results:

 
 
  1. parseInt("8"); //8  
  2. parseInt("08"); //0 

Therefore, we usually specify the second parameter of parseInt as follows:

 
 
  1. parseInt("8", 10); //8  
  2. parseInt("08", 10); //8 

ECMAScript5: ECMAScript no longer supports octal parsing assumptions. In addition, if the second parameter of parseInt is ignored, JSLint warning will be triggered.

String replacement

The string replacement function only replaces the first matching item, and does not replace all the expected matching items. The following code:

 
 
  1. "Bob". replace ("B", "x"); // "xob"
  2. "Bob". replace (/B/, "x"); // "xob" (Regular Expression used)

If you want to replace all the matching items, you can use a regular expression and add a global modifier to it, as shown in the following code:

 
 
  1. "bob".replace(/b/g, "x"); // "xox"  
  2. "bob".replace(new RegExp("b", "g"), "x"); // "xox" (alternate explicit RegExp) 

The global modifier ensures that the replacement function does not stop replacing the next matching item after finding the first matching item.

The "+" operator performs the addition operation and the string connection operation.

As another weak language, php can use the "." operator to connect strings. Javascript is not like this-so when the operand is a string, "a + B" usually performs the connection operation. If you want to add a number, you need to note that the input content may be of the string type. Therefore, before performing the add operation, you need to convert it to the numeric type, the Code is as follows:

 
 
  1. 1 + document. getElementById ("inputElem"). value; // connection operation
  2. 1 + Number (document. getElementById ("inputElem"). value); // Add operation

Note that the subtraction operation will convert the operand to the numeric type. The Code is as follows:

 
 
  1. "3" - "1"; // 2 

Although you want to subtract a string from another string by subtraction, some logical errors may occur.

Most of the time, we use numbers and empty strings to add numbers into strings. The Code is as follows:

 
 
  1. 3 + ""; // "3" 

But this is not good, so we can replace the above method with String (3.

Typeof

Typeof returns the type of an instance of the basic javascript type. Array is not a basic type, so the typeof Array Object will return the Object. The Code is as follows:

 
 
  1. typeof {} === "object" //true  
  2. typeof "" === "string" //true  
  3. typeof [] === "array"; //false 

When you use this operator for your object instance, you will get the same result (typeof = "object ").

In addition, "typeof null" will return "object", which is a bit strange.

Instanceof

Instanceof returns whether the specified object is an instance constructed by a class. This is helpful for us to check whether the specified object is of a custom type. However, if you create a built-in type using text syntax, the error may be returned. The Code is as follows:

 
 
  1. "hello" instanceof String; //false  
  2. new String("hello") instanceof String; //true 

Because Array is not actually a built-in type (just disguised as a built-in type-you cannot get the expected result by using typeof), but you can get the expected result by using instanceof. The Code is as follows:

 
 
  1. ["item1", "item2"] instanceof Array;  //true  
  2. new Array("item1", "item2") instanceof Array;  //true 

Alas, no! In general, if you want to test the type of Boolean, String, Number, or Function, you can use typeof. For any other type, you can use instanceof for testing.

Oh, another point is that in a function, there is a predefined variable named "arguments", which is passed to the function in the form of an array. However, it is not a real array, it is just an object similar to an array, with the length attribute and the attribute value ranges from 0 to length. Very strange... you can use the following tips to convert it into a real array:

 
 
  1. var args = Array.prototype.slice.call(arguments, 0); 

This is the same for the NodeList objects returned by getElementsByTagName-they can all be converted to an appropriate array using the above Code.

Eval

Eval can parse and execute strings in the form of javascript code, but we generally do not recommend this. Because eval is very slow-When javascript is loaded into the browser, it will be compiled at the cost of Code; however, every time an eval expression is encountered during execution, the compilation engine will restart to execute compilation, the price is too high. This is also ugly, and there are many examples of eval abuse. In addition, the Code in eval will be executed within the current range, so it can modify local variables and add something unexpected to your scope.

JSON conversion is often done. We usually use "var obj = eval (jsonText);" for conversion. However, almost all browsers now support local JSON objects. You can use "var obj = JSON. parse (jsonText);" to replace the previous code. On the contrary, you can use "JSON. stringify" to convert a JSON object to a string. Even better, you can use "jQuery. parseJSON" to complete the above work.

The first parameter of the setTimeout and setInterval functions can be parsed and executed using a string as the function body. Of course, we do not recommend this. We can use actual functions instead.

Finally, the Function constructor is very similar to eval. The only difference is that the Function constructor is executed globally.

With

The with expression provides you with a shorthand Method for accessing object attributes, but whether or not we should use it still has a conflict of opinion. Douglas Crockford does not like it very much. John Resig found a lot of clever use of with in his book, but he also admitted that this will affect performance and cause some confusion. Let's take a look at the separated with code block. It cannot tell us exactly what is being executed. The Code is as follows:

 
 
  1. with (obj) {  
  2.     bob = "mmm";  
  3.     eric = 123;  

Have I just modified a local variable named bob? Or have I set obj. bob? If obj. bob has been defined, it will be reset to "mmm ". Otherwise, if another bob is in this range, it will be changed. Otherwise, the global variable bob will be set. Finally, the following statement can clearly express your meaning:

 
 
  1. obj.bob = "mmm";  
  2. obj.eric = 123; 

ECMAScript5 Note: ES5 strictly does not support the with expression.


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.