JavaScript Tutorial Notes 1: Basic Types

说明:

Javascript tutorial (学习笔记) 系列基本上转载自 “A re-introduction to JavaScript (JS Tutorial)“, 原文链接有中文版本, 但是我这里还是直接转载英文的, 觉得有些中文翻译的不地道, 还不如直接看英文, 在转载的内容上我用红色或者蓝色表示出了自己学习过程中的觉得重点的地方, 然后我自己觉得原文不清楚的地方我自己加了注释和自己写的代码例子, 这些都是inline的, 行文基本上是原文的顺序. 所以总体上这一系列基本上算是转载加上自己学习过程中的心得体会. 这一篇是第一篇:

Introduction

Unlike most programming languages, the JavaScript language has no concept of input or output. It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms for communicating with the outside world. The most common host environment is the browser, but JavaScript interpreters can also be found in Adobe Acrobat, Photoshop, Yahoo!’s Widget engine, as well as server side environments such as node.js.

Overview

JavaScript is an object oriented dynamic language; it has types and operators, core objects, and methods. Its syntax comes from the Java and C languages, so many structures from those languages apply to JavaScript as well. One of the key differences is that JavaScript does not have classes; instead, the class functionality is accomplished by object prototypes. The other main difference is that functions are objects, giving functions the capacity to hold executable code and be passed around like any other object.

Let’s start off by looking at the building block of any language: the types. JavaScript programs manipulate values, and those values all belong to a type. JavaScript’s types are:

… oh, and Undefined and Null, which are slightly odd. And Arrays, which are a special kind of object. And Dates and Regular Expressions, which are objects that you get for free. And to be technically accurate, functions are just a special type of object. So the type diagram looks more like this:

  • Number
  • String
  • Boolean
  • Object
    • Function
    • Array
    • Date
    • RegExp
  • Null
  • Undefined

And there are some built in Error types as well. Things are a lot easier if we stick with the first diagram, though.

Numbers

Numbers in JavaScript are “double-precision 64-bit format IEEE 754 values”, according to the spec. This has some interesting consequences. There’s no such thing as an integer in JavaScript, for example

> 3/5
> 0.6 //输出的不是整型0, 如果是C语言的就是0了, 而是小数0.6, 这就是所谓的there is no such thing as integer in JS

so you have to be a little careful with your arithmetic if you’re used to math in C or Java. Watch out for stuff like:

0.1 + 0.2 == 0.30000000000000004

In practice, integer values are treated as 32-bit ints (and are stored that way in some browser implementations), which can be important for bit-wise operations. For details, see The Complete JavaScript Number Reference.

The standard numeric operators are supported, including addition, subtraction, modulus (or remainder) arithmetic and so forth. There’s also a built-in object that I forgot to mention earlier called Math to handle more advanced mathematical functions and constants:

Math.sin(3.5);
var d = Math.PI * r * r;

You can convert a string to an integer using the built-in <a title="en/Core_JavaScript_1.5_Reference/Global_Functions/parseInt" href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt" target="_blank">parseInt()</a> function. This takes the base for the conversion as an optional second argument, which you should always provide:

> parseInt("123", 10)
123
> parseInt("010", 10)
10

If you don’t provide the base, you can get surprising results in older browsers (pre-2013):

> parseInt("010")
8

That happened because the parseInt function decided to treat the string as octal due to the leading 0.

If you want to convert a binary number to an integer, just change the base:

> parseInt("11", 2)
3

Similarly, you can parse floating point numbers using the built-in <a title="en/JavaScript/Reference/Global Objects/parseFloat" href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat" target="_blank">parseFloat()</a> function which uses base 10 always unlike its parseInt() cousin.

You can also use the unary + operator to convert values to numbers:

> + "42"
42

A special value called <a title="en/Core_JavaScript_1.5_Reference/Global_Properties/NaN" href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/NaN" target="_blank">NaN</a> (short for “Not a Number”) is returned if the string is non-numeric:

> parseInt("hello", 10)
NaN

NaN is toxic: if you provide it as an input to any mathematical operation the result will also be NaN:

> NaN + 5
NaN

You can test for NaN using the built-in <a title="en/Core_JavaScript_1.5_Reference/Global_Functions/isNaN" href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN" target="_blank">isNaN()</a> function:

> isNaN(NaN)
true

JavaScript also has the special values <a title="en/Core_JavaScript_1.5_Reference/Global_Properties/Infinity" href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Infinity" target="_blank">Infinity</a> and -Infinity:

> 1 / 0
Infinity
> -1 / 0
-Infinity

You can test for Infinity-Infinity and NaN values using the built-in <a title="en/Core_JavaScript_1.5_Reference/Global_Functions/isFinite" href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isFinite" target="_blank">isFinite()</a> function:

> isFinite(1/0)
false
> isFinite(-Infinity)
false
> isFinite(NaN)
false
Note: The parseInt() and <a title="en/JavaScript/Reference/Global Objects/parseFloat" href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat" target="_blank">parseFloat()</a> functions parse a string until they reach a character that isn’t valid for the specified number format, then return the number parsed up to that point. However the “+” operator simply converts the string to NaN if there is any invalid character in it. Just try parsing the string “10.2abc” with each method by yourself in the console and you’ll understand the differences better.
//关于上面的note, 我的测试代码以及结果如下
> parseInt("10.2abc");
10
> parseFloat("10.2abc");
10.2
> + "10.2abc"
NaN

Strings

Strings in JavaScript are sequences of characters. More accurately, they’re sequences of Unicode characters, with each character represented by a 16-bit number. This should be welcome news to anyone who has had to deal with internationalisation.

If you want to represent a single character, you just use a string of length 1.

To find the length of a string, access its <a title="en/Core_JavaScript_1.5_Reference/Global_Objects/String/length" href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/length" target="_blank">length</a> property:

> "hello".length
5

There’s our first brush with JavaScript objects! Did I mention that strings are objects too? They have methods as well:

> "hello".charAt(0)
h
> "hello, world".replace("hello", "goodbye")
goodbye, world
> "hello".toUpperCase()
HELLO
Written on August 27, 2013