Preliminary Exploration of javascript Functions (II): Preliminary Exploration of javascript Functions

Source: Internet
Author: User

Preliminary Exploration of javascript Functions (II): Preliminary Exploration of javascript Functions

JavascriptPredefined functions:

The javascript engine has a set of built-in functions that can be called at any time.

These built-in functions include:

1. parseInt ()

2. parseFloat ()

3. isNaN ()

4. isFinite ()

5. encodeURI ()

6. decodeURI ()

7. encodeURIComponent ()

8. decodeURIComponent ()

9. eval ()

==========================>>>>>

  Black box Functions

Generally, when we call a function, the program does not need to know the internal work details of the function. We can regard it as a black box. We only need to pass some parameters to it to get the results returned by her output.

This kind of thinking can be applied to any function.

<============================

ParseInt:

The parseInt () function parses a string and returns an integer. That is, parseInt (string, radix );

There are two methods to call a function:

1. Specify radix. This is also the recommended method. Unfortunately, I didn't do this before.

2. Do not specify radix, that is, parseInt (string ). Although simple, there are many rules, which is the core of this article.

ParseInt (string, radix)
Radix indicates the conversion base, which is commonly referred to as binary, octal, decimal, and hexadecimal. The range is from 2 ~ 36, but when we call this method in JS, the conversion is basically based on 10.

If this parameter is smaller than 2 or greater than 36, parseInt () returns NaN.

The detailed rules for applying the "string" parameter are as follows:

1) if they are all letters, NaN is returned, for example:

 window.onload = function testParse() {          alert(parseInt("abc", 10)); }

2) If none of them are letters, 123 is returned, for example:

 window.onload = function testParse() {         alert(parseInt("123", 10)); }

3) if both letters and numbers exist, for example:

window.onload = function testParse() {         alert(parseInt("1x2bc", 10));  // 1         alert(parseInt("df2bc", 10));  // NaN}

Two rules are involved:

1) if the parameter "string" starts with a number, convert all numbers before the first letter appears. in the above example, the first letter that appears is 'x'. Take the previous digit string and only one digit is '1'. Then 1 is returned.

2) If the parameter "string" starts with a letter, NaN is directly returned.

 

The above description is based on the explanation of ECMAScript (officially translated, very powerful ):

The parseInt () method first checks the character at the position 0 to determine whether it is a valid number. If not, the method returns NaN and does not continue to perform other operations. However, if the character is a valid number, this method will view the characters at position 1 and perform the same test. This process continues until a non-valid number is found. At this time, parseInt () converts the string before this character into a number.

  

  ParseFloat

The parseFloat () function parses a string and returns a floating point number.

This function specifies whether the first character in the string is a number. If yes, the string is parsed until it reaches the end of the number, and then the number is returned as a number instead of a string.

Syntax: parseFloat (string); that is to say, the default value is decimal. Others are basically the same as above.

Tips and comments

Note:Only the first number is returned in the string.

Note:Spaces at the beginning and end are allowed.

Note:If the first character of a string cannot be converted to a number, parseFloat () returns NaN.

 

IsNaN

With isNaN (), we can determine whether an input value is a number that can be used in arithmetic operations. Therefore, you can check whether the call of parseInt () and parseFloat () is successful.

isNaN(NaN) // trueisNaN(123) // falseisNaN(1.45) // falseisNaN('abc123') // true

 

This function will also try to convert the accepted parameters into numbers.

isNaN('123') // falseisNaN('abc123') // true

 

NaN = NaN // false

 

IsFinite

IsFinite () can detect whether the input is a number that is neither Infinity nor NaN.

isFinite(InFinity)  // falseisFinite(-Infinity)  // falseisFinite(12) // trueisFinite(1e309) // false

 

 

Javascript coding problems Local/Unicode

You may be confused about "local. At the beginning, I didn't understand it either. It should be a conversion between encodings. Because local characters are encoded, it is reasonable to convert the encoding to Unicode encoding. In fact, Unicode encoding for all country characters is definite, no matter which Mandarin you enter.

Unicode decimal and hexadecimal encoding:

& #20363; & #23376; & #108; & #105; & #122; & #105;
& # X4f8b; & # x5b50; & # x6c; & # x69; & # x7a; & # x69;

The local JavaScript code for Unicode conversion is as follows:

function nativeToUnicode(str) {    var des = [];    for (var i = 0; i < str.length; i++)        des.push("&#" + str.charCodeAt(i) + ";");        //des.push("&#x" + str.charCodeAt(i).toString(16) + ";");    return des.join("");}

The JavaScript code for Unicode to local conversion is as follows:

function unicodeToNative(str) {    var src = str.match(/&#(\d+);/g);    if (src != null) {        var des = [];        for (var i = 0; i < src.length; i++)            des.push(String.fromCharCode(src[i].replace(/[&#;]/g, "")));        return des.join("");    }    return "";}

Note:

  • The String. charCodeAt () method returns the Unicode encoding of characters at the specified position. The returned value is an integer between 0 and 65535.
  • The String. fromCharCode () method accepts a specified Unicode value and returns a String.

 

UTF-8/local

UTF-8 is one of the Unicode implementation methods, the fixed length encoding into variable length, reduce the storage and transmission overhead. The following example shows that Chinese characters are encoded, but English characters that can be expressed in one byte remain unchanged.

UTF-8 code:

& # X4F8B; & # x5B

The JavaScript code for locally converting the UTF-8 is as follows:

function navtiveToUTF8(str) {    return str.replace(/[^\u0000-\u00FF]/g, function ($0) { return escape($0).replace(/(%u)(\w{4})/gi, "&#x$2;") });}

The UTF-8 converts the local JavaScript Code as follows:

function utfToNative(str) {    return unescape(str.replace(/&#x/g, '%u').replace(/;/g, ''));}

Note:

  • The escape () function can encode a string so that the string can be read on all computers.
  • The unescape () function can decode strings encoded by escape.

 

Local/ASCII

ASCII code conversion or non-ASCII encoding:

\ U4f8b \ u5b50lizi

\ U4f8b \ u5b50 \ u006c \ u0069 \ u007a \ u0069

The JavaScript code for locally converting ASCII is as follows:

function nativeToASCII(str, isIgnoreLetter) {    var character = str.split("");    var ascii = [];    for (var i = 0; i < character.length; i++) {        var code = Number(character[i].charCodeAt(0));        if (!isIgnoreLetter || code > 127) {            var charAscii = code.toString(16);            charAscii = new String("0000").substring(charAscii.length, 4) + charAscii;            ascii.push("\\u" + charAscii);        }        else {            ascii.push(character[i]);        }    }    return ascii.join("");}

The local JavaScript code for ASCII conversion is as follows:

function asciiToNative(str) {    var character = str.split("\\u");    var res = character[0];    for (var i = 1; i < character.length; i++) {        var code = character[i];        res += String.fromCharCode(parseInt("0x" + code.substring(0, 4)));        if (code.length > 4) {            res += code.substring(4, code.length);        }    }    return res;}

 

Local/URI Encoding

The URI encoding does not use the above encoding. It is mainly for security reasons, so that the link content cannot be clearly viewed, to prevent malicious peek. The following is the cnblogs "look for" Search link and encode it.

Example 4:

Http://zzk.cnblogs.com? W = example lizi & t =

URI encoding and component encoding are:

Http://zzk.cnblogs.com? W = % E4 % BE % 8B % E5 % AD % 90 lizi & t =

Http % 3A % 2F % 2Fzzk.cnblogs.com % 2Fs % 3Fw % 3D % E4 % BE % 8B % E5 % AD % 90 lizi % 26 t % 3D

Note:

  • The encodeURI () function can encode a string as a URI.
  • The decodeURI () function can decode the URI encoded by the encodeURI () function.
  • The encodeURIComponent () function can encode a string as a URI component.
  • The decodeURIComponent () function can decode the uri of the encodeURIComponent () function.

 

For the eval () function, see the next section (. Required _ parameters ._.)/~~~

For more information, see ================== "" http://www.cnblogs.com/liuning8023/archive/2012/12/09/2810518.html

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.