官术网_书友最值得收藏!

Pre-defined Functions

There are a number of functions that are built into the JavaScript engine and available for you to use. Let's take a look at them. While doing so, you'll have a chance to experiment with functions, their parameters and return values , and become comfortable in working with them. The list of the built-in functions is:

  • parseInt()
  • parseFloat()
  • isNaN()
  • isFinite()
  • encodeURI()
  • decodeURI()
  • encodeURIComponent()
  • decodeURIComponent()
  • eval()

Tip

The Black Box Function

Often, when you invoke functions, your program doesn't need to know how these functions work internally. You can think of a function as a black box: you give it some values (as input parameters) and then you take the output result it returns. This is true for any function—one that's built into the JavaScript engine, one that you create, or one that a co-worker or someone else created.

parseInt()

parseInt() takes any type of input (most often a string) and tries to make an integer out of it. If it fails, it returns NaN.

>>> parseInt('123')

123

>>> parseInt('abc123')

NaN

>>> parseInt('1abc23')

1

>>> parseInt('123abc')

123

The function accepts an optional second parameter, which is the radix, telling the function what type of number to expect—decimal, hexadecimal, binary, and so on. For example trying to extract a decimal number out of the string FF makes no sense, so the result is NaN, but if you try FF as a hexadecimal, then you get 255.

>>> parseInt('FF', 10)

NaN

>>> parseInt('FF', 16)

255

Another example would be parsing a string with a base 10 (decimal) and base 8 (octal).

>>> parseInt('0377', 10)

377

>>> parseInt('0377', 8)

255

If you omit the second parameter when calling parseInt(), the function will assume 10 (a decimal), with these exceptions:

  • If you pass a string beginning with 0x as a first parameter, then the second is assumed to be 16 (a hexadecimal number is assumed)
  • If the first parameter starts with 0, the function assumes 8 as a second parameter (an octal number is assumed)
>>> parseInt('377') 

377

>>> parseInt('0377') 

255

>>> parseInt('0x377') 

887

The safest thing to do is to always specify the radix. If you omit the radix, your code will probably still work in 99% of cases (because most often you parse decimals), but every once in a while it might cause you a bit of hair loss while debugging some problems. For example, imagine you have a form field that accepts calendar days and the user types 08; if you omit the radix you might get unexpected results.

parseFloat()

parseFloat() is the same as parseInt() but it also looks for decimals when trying to figure out a number from your input. This function takes only one parameter.

>>> parseFloat('123')

123

>>> parseFloat('1.23')

1.23

>>> parseFloat('1.23abc.00')

1.23

>>> parseFloat('a.bc1.23')

NaN

As with parseInt(), parseFloat() gives up at the first occurrence of an unexpected character, even though the rest of the string might have usable numbers in it.

>>> parseFloat('a123.34')

NaN

>>> parseFloat('12a3.34')

12

parseFloat() understands exponents in the input (unlike parseInt()).

>>> parseFloat('123e-2')

1.23

>>> parseFloat('123e2')

12300

>>> parseInt('1e10')

1

isNaN()

Using isNaN() you can check if an input value is a valid number that can safely be used in arithmetic operations. This function is also a convenient way to check whether parseInt() or parseFloat() succeeded.

>>> isNaN(NaN)

true

>>> isNaN(123)

false

>>> isNaN(1.23)

false

>>> isNaN(parseInt('abc123'))

true

The function will also try to convert the input to a number:

>>> isNaN('1.23')

false

>>> isNaN('a1.23')

true

The isNaN() function is useful because NaN is not equal to itself. So, surprisingly, NaN === NaN is false.

isFinite()

isFinite() checks whether the input is a number that is neither Infinity nor NaN.

>>> isFinite(Infinity)

false

>>> isFinite(-Infinity)

false

>>> isFinite(12)

true

>>> isFinite(1e308)

true

>>> isFinite(1e309)

false

If you wonder about the results returned by last two calls, remember from the previous chapter that the biggest number in JavaScript is 1.7976931348623157e+308.

Encode/Decode URIs

In a URL (Uniform Resource Locator) or a URI (Uniform Resource Identifier), some characters have special meanings. If you want to "escape" those characters, you can use the functions encodeURI() or encodeURIComponent(). The first one will return a usable URL, while the second one assumes you're only passing a part of the URL, like a query string for example, and will encode all applicable characters.

>>> var url = 'http://www.packtpub.com/scr ipt.php?q=this and that';
>>> encodeURI(url);

"http://www.packtpub.com/scr%20ipt.php?q=this%20and%20that"

>>> encodeURIComponent(url);

"http%3A%2F%2Fwww.packtpub.com%2Fscr%20ipt.php%3Fq%3Dthis%20and%20that"

The opposites of encodeURI() and encodeURIComponent() are decodeURI() and decodeURIComponent() respectively. Sometimes, in older code, you might see the similar functions escape() and unescape() but these functions have been deprecated and should not be used.

eval()

eval() takes a string input and executes it as JavaScript code:

>>> eval('var ii = 2;')
>>> ii

2

So eval('var ii = 2;') is the same as simply var ii = 2;

eval() can be useful sometimes, but should be avoided if there are other options. Most of the time there will be alternatives and, in most cases, the alternatives are more elegant and easier to write and maintain. "Eval is evil" is a mantra you can often hear from seasoned JavaScript programmers. The drawbacks of using eval() are:

  • Performance—it is slower to evaluate "live" code, than to have the code directly in the script.
  • Security—JavaScript is powerful, which also means it can cause damage. If you don't trust the source of the input you pass to eval(), just don't use it.

A Bonus—the alert() Function

Let's take a look at one very common function—alert(). This is not part of the core JavaScript (it is not in the ECMA specification), but it is provided by the host environment—the browser. It shows a string of text in a message box. It can also be useful for debugging sometimes, although the Firebug debugger is a much better tool for this purpose.

Here's a screenshot showing the result of executing the code alert("hello!")

A Bonus—the alert() Function

Before using this function, bear in mind that it blocks the browser thread, meaning that no other code will be executed until the user closes the alert. If you have a busy AJAX-type application, it is generally not a good idea to use alert().

主站蜘蛛池模板: 富宁县| 鲁山县| 云霄县| 彰武县| 青龙| 罗城| 波密县| 米易县| 乐亭县| 海阳市| 洪雅县| 磐安县| 德江县| 碌曲县| 专栏| 监利县| 平塘县| 秦皇岛市| 华安县| 菏泽市| 仙游县| 眉山市| 莒南县| 安丘市| 宜都市| 巩义市| 镇赉县| 类乌齐县| 安龙县| 二手房| 堆龙德庆县| 尚义县| 文水县| 和顺县| 开远市| 荣成市| 铁力市| 密云县| 陵水| 湖南省| 漠河县|