JavascriptparseInt-javascript skills

Source: Internet
Author: User
I vaguely remember the first time I encountered the strange problem of parseInt, I thought I was excited when I found the BUG of IE. I vaguely remembered the ins and outs and cheered for my own experience.

I vaguely remember the feeling of helplessness and determination after I was tortured by this same problem for countless times.

First of all, I must thank those who have repeatedly and repeatedly made similar mistakes even though I have emphasized this issue for countless times.
Without their repeated encouragement, I may not seriously consider the solution to this problem.
Second, we must thank the author and translator of JavaScript advanced programming.
Here I have gained some inspiration to solve this problem. Otherwise, I still need to pay attention to what should I pay attention to when I emphasize parseInt.


At the same time, we hope to leave a solution here.
The ideas and ideas for solving the problem, as well as the experience on the opposite sides of the problem, should be retained here.

Problem:
The problems that occurred a long time ago do not need to be recalled.
This issue is very simple. When comparing the two months, because the month is extracted from the string, it is converted using parseInt.
The result after parseInt ("08") is 0.
For the reason, see the following JavaScript advanced programming 19 ~ 20 pages to explain the parseInt function.

The parseInt () method also has the base mode, which can convert binary, octal, hexadecimal, or any other hexadecimal string to an integer.
The base is specified by the second parameter of the parseInt () method. to parse the hexadecimal value, you need to call the parseInt () method as follows:

The Code is as follows:


Var iNum1 = parseInt ("AF", 16); // return 175


Of course, you can call the parseInt () method like this for binary, octal, or decimal (default mode:

The Code is as follows:


Var iNum1 = parseInt ("10", 2); // return 2
Var iNum2 = parseInt ("10", 8); // return 8
Var iNum3 = parseInt ("10", 10); // return 10


If the decimal number contains the leading 0, it is best to use base 10 to avoid unexpected octal values. For example:

Var iNum1 = parseInt ("010"); // return 8
Var iNum2 = parseInt ("010", 8); // return 8
Var iNum3 = parseInt ("010", 10); // return 10

In this Code, both lines of code parse the character "010" into a number.

The first line of code regards this string as the octal value. The method for parsing this string is the same as that of the second line of code (The Declaration base is 8. The last line of Code declares that the base number is 10, so iNum3 is equal to 10 at last.

First try:
The previous solution was to let everyone discard the parseInt function and replace it with parseFloat.
But as a person, what should I do "?
The best way is to keep the "shape" of parseInt and discard the "God" of parseInt ".
So I thought of JavaScript advanced programming 87 ~ 88-page description of "redefinition of existing methods.
3.6.2 redefinition of existing methods
Just like defining new methods for existing classes, you can also redefine existing methods.
As described in the previous chapter, the function name is just a pointer to the function, so you can easily point it to other functions. What happens if you modify the local method, such as toString?

Function. prototype. toString = function (){
Return "Function code hidden ";
}
The preceding code is completely legal and the running result is exactly as expected:
Function sayHi (){
Alert ("Hello! ");
}
Alert (sayHi. toString (); // output "Function code hidden"
You may still remember that the toString () method of Function is usually used to output the source code of the Function in Chapter 2nd.
Overwrite this method and return another string (in this example, return "Function code hidden ").
But what about the original function pointed to by toString? It will be recycled by useless storage unit recycler because it is completely deprecated.
There is no way to restore the original function. Therefore, before overwriting the original method, it is safer to store its pointer for future use.
You may even call the original method in the new method in some way:
Function. prototype. originalToString = Function. prtotype. toString;
Function. prototype. toString = function (){
If (this. originalToString (). length> 100 ){
Return "Function too leng to display ."
} Else {
Return this. originalToString ();
}
In this Code, the first line of code references the current toString () method.

Saved in originalTo-String. The custom method overwrites the toString () method.
The new method checks whether the source code length of the function is greater than 100.
If yes, an error message is returned, indicating that the function code is too long. Otherwise, the originalToString () method is called to return the source code of the function.

Based on this example, you only need to write a line based on the gourd image.
Global. prototype. parseInt = Global. prototype. parseFloat;
Then the parseInt function is actually a function that has its table, but what it does in its stomach is the parseFloat activity.
However, at the same time, a fatal problem is at the forefront.
That is, the Global Object in JavaScript, just like God, is just a concept.
For instructions, see the description of "built-in objects" On page 70 of "JavaScript advanced programming" below.
Global objects are the most special objects in ECMAScript, because they do not exist at all.
If you try to write the following code, you will get an error:
Var pointer = Global;
The error message shows that Global is not an object, but didn't Global be an object just now?
Yes. The main concept to be understood here is that there are no independent functions in ECMAScript, and all functions must be methods of an object.
Functions described earlier in this book, such as isNaN (), isFinite (), parseInt (), and parseFloat (), all look like independent functions.
In fact, they are all Global object methods.

As a result, I checked on the internet how to get the Global object, or how to use Global. prototype to change the parseInt function.
As a result, God is a god, and even Google, the famous "soushen.com", cannot be found.
When I want to give up, I should say "dead and then born ". Suddenly, just like a global function, parseInt does not need to be called.
That's not to say, just change the above sentence to parseInt = parseFloat?
Sure enough, God is everywhere !!! Easy to use !!!


In-depth study:
The problem is basically solved. Note that when JavaScript loading fails, the subsequent statements will not be loaded and executed.
Therefore, this sentence must be executed in the first sentence. Now, a common JavaScript library is created, and the library file must be introduced to each page in the future.
Therefore, this sentence is placed in the first line of the JavaScript universal keystore library, so you can rest assured.
However, when I write comments for this section of code, especially how to list applications, I find the following code problems:
Alert (parseInt ("010", 2); // 10
Alert (parseInt ("010", 8); // 10
Alert (parseInt ("010", 10); // 10
The return value of each processing operation is 10, that is, binary, octal, and hexadecimal parseInt can be processed.
If the parseInt of a single parameter causes a lot of trouble, we still want to retain its special function for the parseInt of the two parameters that are not in trouble.
Therefore, further improvement is required.
When using the parseInt function, it is necessary to pass the number of parameters for judgment and processing.
If there is only one parameter, call parseFloat to return the result.
If there are more than two parameters, call the processing of the two parameters parseInt and return the result.
The arguments object is used to determine the number of parameters. For details, see JavaScript advanced programming 53 ~ 54-page description of the arguments object.
In function code, the special object arguments can be accessed without explicitly specifying the parameter names.
For example, in the sayHi () function, the first parameter is message.
You can also access this value using arguments [0], that is, the value of the first parameter (the first parameter is at the position 0, and the second parameter is at the position 1, and so on ).
Therefore, you can rewrite the function without specifying the parameter:
Function sayHi (){
If (arguments [0] = "bye "){
Return;
}
Alert (arguments [0]);
}
The following code is available:
OriginalparseInt = parseInt;
ParseInt = function (){
If (arguments. length = 1 ){
Return parseFloat (arguments [0]);
} Else {
Return originalparseInt (arguments [0], arguments [1]);
}
In this Code, we transformed the parseInt so that it can be processed differently based on the number of parameters.
Use a new variable originalparseInt to retain the prototype of parseInt.
In this way, even if parseInt is transformed, the original features of parseInt can still be used through the reserved prototype variable originalparseInt.

Back to pu Zhen:
The Code was written to this book and thought everything was okay, but it was said that the parseInt function had completely erased the processing of binary and octal functions.
Think too. The processing is too extreme. I only want to replace the annoying parseInt function with parseFloat.
If we use binary or octal numeric conversion, we have to use the prototype new variable originalparseInt of the parseInt function that we have struggled to retain.
In fact, our wish is very simple.
When there is only one parameter in the parseInt function, we want it to simply handle the 10-in-order conversion. Don't create some headaches because of the first 0.
When we use the second parameter and want it to process binary and octal, we can still use the existing parseInt function.
The final code is as follows:
Considering the size of js files, reduce the amount of code as much as possible. Replace originalparseInt with $ parseInt.
In addition, the super-long built-in Object Name arguments is directly replaced with a letter a, which saves a lot of code for this object four times.


Trigger:
The parseInt function is created again.
In fact, based on the experience of this transformation, we can transform the JavaScript method with the annoying features similar to parseInt.
For example, escape and unescape can be replaced by the recommended method if they are not recommended by W3C organizations.

Escape = encodeURI;
Unescape = decodeURI;
Based on this experience, we can solve similar problems in the future.
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.