Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the traps in Javascript

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "what are the traps in Javascript". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Functions and operators

Double equal sign (strictly use = instead of =)

Type casting occurs when the = = operator compares, which means it can compare two different types of objects, and it will try to convert the two objects to the same type before performing the comparison, for example:

"1" = 1 / / true

However, this often misleads us, and we don't need to compare in this way. In the above example, we can first convert the string to a numeric type, and then compare it with the type-sensitive triple equal sign (=), such as:

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

Or, better yet, make sure that the type of Operand you put first is correct.

Because the double equal sign has the behavior of casting, it breaks the general rule of transitivity, which is a bit scary, see the following column:

"" = 0 / / true

-the empty string is cast to the number 0.

0 = "0" / / true

-the number 0 is cast to the string "0"

"" = "0" / / false

-both operands are strings, so no cast copy code is performed

If you use the triple equal sign, all three of the above comparisons return false.

ParseInt does not use 10 as the numeric base (use parseInt to specify the second parameter)

If you omit the second parameter of parseInt, the cardinality of the number will be determined by the following rule:

The default cardinality is 10, that is, parsing in decimal

If the number starts with 0x, then the cardinality is 16, which is parsed in hexadecimal

If the number starts with 0, then the cardinality is 8, which means parsing in octal

A common mistake is that we ask the user to enter a number that starts with 0, which parses it in octal mode, so we see the following effect:

ParseInt ("8"); / / 8

ParseInt ("08"); / / 0 copy the code

Therefore, we often specify the second parameter of parseInt, as shown below:

ParseInt ("8", 10); / / 8

ParseInt ("08", 10); / / 8 copy code

Note on ECMAScript5: ECMAScript no longer supports the octal parsing assumption, and omitting the second parameter of parseInt will cause a warning from JSLint.

String substitution (the first argument of the replace function supports strings and regularities, and the second parameter supports strings and functions. For more information, please see http://www.w3school.com.cn/js/jsref_replace.asp)

The string replacement function will only replace the first match, not all the matches you expect. The code is as follows:

"bob" .replace ("b", "x"); / / "xob"

"bob" .replace (/ bbind, "x"); / / "xob"

(using regular expressions) copy the code

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

"bob" .replace (/ bswap g, "x"); / / "xox"

"bob" .replace (new RegExp ("b"

"g"), "x"); / / "xox"

(alternate explicit RegExp) copy the code

The global modifier ensures that the replacement function does not stop replacing the next match after it finds the first match.

The "+" operator performs addition and string concatenation operations

As another weakly typed language, php can use "." Operator concatenates strings. This is not the case with Javascript-so "aplb" usually performs concatenation operations when the Operand is a string. If you want to perform a number addition, you should pay attention, because the input may be of a string type, so you need to convert it to a number type before performing the addition operation, as follows:

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

1 + Number (document.getElementById ("inputElem") .value); / / copy the code by adding operation

It is important to note that the subtraction operation attempts to convert the Operand to a numeric type, as follows:

"3"-"1"; / / 2

Although sometimes you want to subtract a string from another string, there are often some logic errors.

In many cases, we use the addition of numbers and empty strings to convert numbers into strings. The code is as follows:

3 + ""; / / "3"

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

Typeof

Typeof this returns the type of an instance of the javascript base type. Array is not really a basic type, so typeof

The Array object will return Object with the following code:

Typeof {}

= = "object" / / true

Typeof ""

= = "string" / / true

Typeof []

= = "array"; / / false copy the code

You will get the same result (typeof = "object") when you use this operator on an instance of your object.

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

Instanceof

Instanceof returns whether the specified object is an instance constructed by a class, which is helpful for us to check whether the specified object is one of the custom types, but if you are a built-in type created with text syntax, you may get an error as follows:

"hello" instanceof String; / / false

New String ("hello") instanceof String; / / true copy the code

Because Array is not really a built-in type (it's just disguised as a built-in type-so you can't get the expected results by using typeof on it), but you can get the desired results by using instanceof, as shown in the code below:

["item1", "item2"] instanceof Array; / / true

New Array ("item1"

"item2") instanceof Array; / / true copy the code

Oh, it sucks! In general, if you want to test Boolean, String, Number, or Function types, you can use typeof, and for any other type, you can use instanceof tests.

Oh, and one more thing, in a function, there is a predefined variable called "arguments", which is passed to function as an array. However, it's not a real array, it's just an array-like object with a length attribute and a property value from 0-length. It's very strange. You can convert it to a real array using the following tricks:

Var args

= Array.prototype.slice.call (arguments, 0)

The same is true for NodeList objects returned by getElementsByTagName-they can all be converted to the appropriate array using the above code.

Eval

Eval can parse and execute strings in the form of javascript code, but in general this is not recommended. Because eval is very slow-when javascript is loaded into the browser, it is compiled into native code; however, every time an eval expression is encountered during execution, the compilation engine will restart the compilation, which is too expensive. And it's ugly, and there are many examples of eval being abused. In addition, the code in eval executes within the current scope, so it can modify local variables and add something unexpected to your scope.

JSON conversion is something we often do; usually we use "var obj = eval (jsonText);" to do the conversion. However, now that almost all browsers support native JSON objects, you can use "var obj = JSON.parse (jsonText);" instead of the previous code. Instead, you can use "JSON.stringify" to convert JSON objects into strings. Even better, you can use "jQuery.parseJSON" to do the above work.

The first argument of the setTimeout and setInterval functions can be parsed and executed with a string as the function body, which is not recommended, of course, but can be replaced by an actual function.

Finally, the constructor of Function is very similar to eval, except that the Function constructor is executed globally.

With

With expressions will give you shorthand access to object properties, but there are still conflicting views on whether we should use it. Douglas Crockford doesn't like it very much. John Resig has found many clever uses of with in his book, but he also admits that this will affect performance and cause a bit of confusion. Let's take a look at our detached block of with code, which cannot tell us exactly what is being executed right now, as shown below:

With (obj)

{

Bob = "mmm"

Eric = 123

} copy the code

Did I just change a local variable called bob? Or have I set up obj.bob? If obj.bob is already defined, it will be reset to "mmm". Otherwise, if there is another bob in this range, then it will be changed. Otherwise, the global variable bob is set. Finally, the following words can express what you mean very clearly:

Obj.bob = "mmm"

Obj.eric = 123; copy the code

ECMAScript5 notes: ES5 strictly no longer supports with expressions.

Types and constructors

Construct built-in types using the "new" keyword

There are Object, Array, Boolean, Number, String, and Function types in Javascript, each of which has its own literal syntax, so there is no need for explicit constructors.

Explicit construction (not recommended) literal syntax (recommended)

Var a = new Object ()

A.greet = "hello"; var a = {greet: "hello"}

Var b = new Boolean (true); var b = true

Var c = new Array ("one", "two"); var c = ["one", "two"]

Var d = new String ("hello"); var d = "hello"

Var e = new Function ("greeting", "alert (greeting);"); var e = function (greeting) {alert (greeting);}; however, if you use the new keyword to construct one of the above types, you will actually get an object of type Object that inherits from the prototype of the type you want to construct (except for the Function type). So although you construct a Number type with the new keyword, it will also be an Object type, as shown in the following code:

Typeof new Number (123) / / "object"

Typeof Number (123) / / "number"

Typeof 123; / / "number" copy the code

The third item above is text grammar, and to avoid conflicts, we should use this method to construct these types.

Use the "new" keyword to construct anything

If you write your own constructor and forget the new keyword, the tragedy happens:

Var Car

= function (colour)

{

This.colour

= colour

}

Var aCar

= new Car ("blue")

Console.log (aCar.colour); / / "blue"

Var bCar

= Car ("blue")

Console.log (bCar.colour); / / error

Console.log (window.colour); / / "blue" copy the code

Calling a function with the new keyword creates a new object, then calls the function in the context of the new object, and finally returns the object. On the contrary, if you do not use new, the key is to call the function, then it will become a global object.

No Integer type

Numerical calculations are relatively slow because there is no Integer type. Only the Number type-Number is a double-precision floating-point (64-bit) type in the IEEE standard. This means that Number causes the following precision rounding error:

0 1 + 0 2 = = 0 3 / / false

Because there is no difference between integers and floats, unlike C# and JAVA, the following code is true:

0.0 = = 0; / / true

Finally, there is a question about Number. How should we implement the following questions:

A = = b; / / true

1max a = = 1max b; / / false copy code

The answer is that according to the Number specification, + 0 and-0 are allowed. + 0 equals-0, but positive infinity is not equal to negative infinity. The code is as follows:

Var a

= 0 * 1; / / the result is 0

Var b

= 0 *-1; / / the result is-0

You can also directly "binge talk 0", but why do you want to do this?

A = = b; / / true:

0 equals-0

1max a = = 1max b; / / false:

Positive infinity does not equal negative infinity copy code

Scope

No block scope

Because you may have noticed the previous point, there is no concept of block scope in javascript, only function scope. Try the following code:

For (var iTunes 0

I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report