您的位置:首页 > Web前端 > JavaScript

JavaScript 1

2012-07-16 16:46 381 查看

词法结构

字符集

区分大小写

空格、换行和格式控制符

unicode转义

标准化

注释

行尾//后的内容为注释

/*与*/之间的文本为注释,可以跨行,但是不能嵌套。

直接量

12数字
1.2小数
"Hello world"字符串
'Hi'字符串
truebool
falsebool
/\w+/giRegExp
null
{x:1,y:1}对象
[1,2,3,4,5]数组

标识符和保留字

标识符以字母、下划线、美元符号开始,后续的字符可以是字母、下划线、美元符、和数字。即匹配/[a-z_$][a-z0-9_$]*/i

关键字或保留字不能用作标识符,预定义的全局变量和函数也应避免用作标识符。

可选的分号

分号(;)表明语句的结束。语句各自独占一行,可以省略语句之间或者语句与闭花括号(})之间的分号。

只有在缺少了分号就无法解析代码的时候,javaScript才会填补分号。(javaScript使语句尽可能的长)

注意以([/+-开始的语句可能会和前一条语句合并解析。

如果在return, break, continue关键字后换行,javascript会在换行处填补分号。也就是说,不能在这三个关键字和其后的表达式之间换行。

++和--操作符可以作为操作数的前缀,也可以用作后缀。为避免歧义,这两个操作符应该和他的操作数放在一行。

类型、值和变量

数字

javascript不区分整数值和浮点数值。但是,javascript的数组索引是32位整数。

负号是一元求反运算符,不是数字直接量语法的组成部分。

整型直接量

\d+

浮点型直接量

(\d+)?\.(\d+)?([Ee][+-]?\d+)?

javaScript中的算术运算

+-*/%

Math.pow(2, 53) // => 9007199254740992: 2 to the power 53
Math.round(.6) // => 1.0: round to the nearest integer
Math.ceil(.6) // => 1.0: round up to an integer
Math.floor(.6) // => 0.0: round down to an integer
Math.abs(-5) // => 5: absolute value
Math.max(x, y, z) // Return the largest argument
Math.min(x, y, z) // Return the smallest argument
Math.random() // Pseudo-random number x where 0 <= x < 1.0
Math.PI // π: circumference of a circle / diameter
Math.E // e: The base of the natural logarithm
Math.sqrt(3) // The square root of 3
Math.pow(3, 1 / 3) // The cube root of 3
Math.sin(0) // Trigonometry: also Math.cos, Math.atan, etc.
Math.log(10) // Natural logarithm of 10
Math.log(100) / Math.LN10 // Base 10 logarithm of 100
Math.log(512) / Math.LN2 // Base 2 logarithm of 512
Math.exp(3) // Math.E cubed

溢出(overflow):当数字运算结果超过上限,结果为Infinity。类似地,负数范围超限结果为-Infinity。基于无穷大的+-*/运算结果还是无穷大。

下溢(underflow):就是无穷小,结果为0。javascript还有一个特殊-0用来表示负无穷小。无穷小无论正负都是0.

非零数被零除返回±Infinity,这时正零、负零会影响返回无穷大的正负号。零除零返回NaN.

无穷大除以无穷大、负数开方、算术运算符与非数字类型的操作数运算时,返回NaN。

NaN和任何值都不相等,包括自身。并且只有NaN和自身不相等(!=)。

isNaN()isFinite()

二进制浮点数和舍入误差

舍入误差只有在比较两个值是否相等时才会对程序有影响。可以这样判断v1,v2是否相等

Math.abs(v1-v2)<0.001//true表示相等

可以采用较小的单位,使用大整数以提高计算的精度。

日期和时间

var then = new Date(2010, 0, 1); // The 1st day of the 1st month of 2010
var later = new Date(2010, 0, 1, // Same day, at 5:10:30pm, local time
17, 10, 30);

var now = new Date(); // The current date and time
var elapsed = now - then; // Date subtraction: interval in milliseconds

later.getFullYear() // => 2010
later.getMonth() // => 0: zero-based months
later.getDate() // => 1: one-based days
later.getDay() // => 5: day of week. 0 is Sunday 5 is Friday.
later.getHours() // => 17: 5pm, local time
later.getUTCHours() // hours in UTC time; depends on timezone
later.toString() // => "Fri Jan 01 2010 17:10:30 GMT-0800 (PST)"
later.toUTCString() // => "Sat, 02 Jan 2010 01:10:30 GMT"
later.toLocaleDateString() // => "01/01/2010"
later.toLocaleTimeString() // => "05:10:30 PM"
later.toISOString() // => "2010-01-02T01:10:30.000Z"; ES5 only

文本

一组由16位值(通常来自Unicode字符集)组成的不可变的有序序列。

字符串直接量

由单引号或双引号定界的字符序列。

字符串直接量可以拆成数行,每行以反斜线结束,反斜线和回车符都不字符串的内容。

var s = "one line\
next line"

转义字符

Sequence Characterrepresented
\0The NUL character\u0000
\bBackspace\u0008
\tHorizontal tab\u0009
\nNewline\u000A
\vVertical tab\u000B
\fForm feed\u000C
\rCarriage return\u000D
\"Double quote\u0022
\'Apostrophe or single quote\u0027
\\Backslash\u005C
\xNNThe Latin-1 character specified by the two hexadecimal digits NN
\uNNNNThe Unicode character specified by the four hexadecimal digits NNNN
If the \ character precedes any character other than those shown in this table, the backslash is simply ignored.

字符串的使用

var msg = "Hello, " + "world"; // Produces the string "Hello, world"
var greeting = "Welcome to my blog," + " " + name;

var s = "hello, world" // Start with some text.
s.length
s.charAt(0) // => "h": the first character.
s.charAt(s.length - 1) // => "d": the last character.
s.substring(1, 4) // => "ell": the 2nd, 3rd and 4th characters.
s.slice(1, 4) // => "ell": same thing
s.slice(-3) // => "rld": last 3 characters
s.indexOf("l") // => 2: position of first letter l.
s.lastIndexOf("l") // => 10: position of last letter l.
s.indexOf("l", 3) // => 3: position of first "l" at or after 3
s.split(", ") // => ["hello", "world"] split into substrings
s.replace("h", "H") // => "Hello, world": replaces all instances
s.toUpperCase() // => "HELLO, WORLD"

s[0] // => "h"
s[s.length - 1] // => "d"

模式匹配

Text between a pair of slashes constitutes a regular expression literal. The second slash in the pair can also be followed by one or more letters, which modify the meaning of the pattern.

var re=/^HTML/ // Match the letters H T M L at the start of a string
var re=/[1-9][0-9]*/ // Match a non-zero digit, followed by any # of digits
var re=/\bjavascript\b/i // Match "javascript" as a word, case-insensitive

var text = "testing: 1, 2, 3"; // Sample text
var pattern = /\d+/g // Matches all instances of one or more digits
pattern.test(text) // => true: a match exists
text.search(pattern) // => 9: position of first match
text.match(pattern) // => ["1", "2", "3"]: array of all matches
text.replace(pattern, "#"); // => "testing: #, #, #"
text.split(/\D+/); // => ["","1","2","3"]: split on non-digits

布尔值

布尔值只有两个值true和false。

undefined null NaN "" 0 都会被转换为布尔值false。

null和undefined

null是关键字,typeof null =="object"

In practice, however, null is typically regarded as the sole member of its own type, and it can be used to indicate "no value" for numbers and strings as well as objects.

undefined是预定义的全局变量,而不是关键字。typeof undefined=="undefined"

The undefined value represents a deeper kind of absence. It is the value of variables that have not been initialized and the value you get when you query the value of an object property or array element that does not exist. The undefined value is also returned by functions that have no return value, and the value of function parameters for which no argument is supplied.

undefined == null会返回true值。undefined===null才会返回false值。null表示no object,undefined表示no subject。

全局对象

global properties like undefined, Infinity, and NaN.

global functions like isNaN(), parseInt(), and eval().

constructor functions like Date(), RegExp(), String(), Object(), and Array().

global objects like Math and JSON.

包装对象

在访问字符串,数字或布尔值的属性时会创建临时对象,这个临时对象叫做包装对象。

包装对象的属性都是只读的,也不能给包装对象定义新属性。

不可变的原始值和可变的对象引用

原始值:undefined null 布尔值 数字 字符串

原始值是不可变的。只有在他们的值相等时他们才相等,对于字符串,他们的长度相等,并且每个字符对应相同,则字符串相等。

对象包括数组、和函数

对象是可变的,他们的值可以修改。对象的比较均是引用的比较,当且仅当他们引用同一个基对象,他们才相等。

类型转换

转换和相等性

显示类型转换

当不通过new运算符调用Boolean(), Number(), String(),或Object()函数时,他们会作为类型转换函数。并按照表所述规则做类型转换。

Object(null) Object(undefined)会返回一个空对象。

x.toString()方法和String(x)方法返回结果一致。如果变量x为null, 或者undefined则抛出类型错误。

运算符会引发隐式的类型转换。

x + "" //等价于String(x)
x - 0  //等价于Number(x)
+ x    //等价于Number(x)
!!x    //等价于Boolean(x)


Number转化为字符串:

var n = 17;
binary_string = n.toString(2); // Evaluates to "10001"
octal_string = "0" + n.toString(8); // Evaluates to "021"
hex_string = "0x" + n.toString(16); // Evaluates to "0x11"

var n = 123456.789;

n.toFixed(0); // "123457"
n.toFixed(2); // "123456.79"
n.toFixed(5); // "123456.78900"

n.toExponential(1); // "1.2e+5"
n.toExponential(3); // "1.235e+5"

n.toPrecision(4); // "1.235e+5"
n.toPrecision(7); // "123456.8"
n.toPrecision(10); // "123456.7890"

parseInt() parseFloat()将字符串解析为数字:

parseInt("3 blind mice") // => 3
parseFloat(" 3.14 meters") // => 3.14
parseInt("-12.34") // => -12
parseInt("0xFF") // => 255
parseInt("0xff") // => 255
parseInt("-0XFF") // => -255
parseFloat(".1") // => 0.1
parseInt("0.1") // => 0
parseInt(".1") // => NaN: integers can't start with "."
parseFloat("$72.47"); // => NaN: numbers can't start with "$"

parseInt("11", 2); // => 3 (1*2 + 1)
parseInt("ff", 16); // => 255 (15*16 + 15)
parseInt("zz", 36); // => 1295 (35*36 + 35)
parseInt("077", 8); // => 63 (7*8 + 7)
parseInt("077", 10); // => 77 (7*10 + 7)


对象转换为原始值

toString()方法:

Object的toString()方法返回"[object Object]"

数组类的toString()方法将每个元素转换为字符串,并在元素之间添加逗号后合并成结果字符串。

函数类的toString()方法返回这个函数的源代码字符串。

日期类的toString()方法返回可读且可以被javascript解析的日期和时间字符串。

RegExp类toString()将返回正则表达式直接量。

({ x: 1, y: 2 }).toString() // => "[object Object]"

[1,2,3].toString() // => "1,2,3"
(function(x) { f(x); }).toString() // => "function(x) {\n f(x);\n}"
(/\d+/g).toString() // => "/\\d+/g"
new Date(2010,0,1).toString() // => "Fri Jan 01 2010 00:00:00 GMT-0800 (PST)"

valueOf()方法:

it is supposed to convert an object to a primitive value that represents the object, if any such primitive value exists.

Wrapper classes define valueOf() methods that return the wrapped primitive value.

Objects are compound values, and most objects cannot really be represented by a single primitive value, so the default valueOf() method simply returns the object itself rather than returning a primitive.

Arrays, functions, and regular expressions simply inherit the default method. Calling valueOf() for instances of these types simply returns the object itself.

The Date class defines a valueOf() method that returns the date in its internal representation: the number of milliseconds since 1970-1-1

对象到字符串的转换:

如果对象具有返回原始值的toString()方法,将这个原始值转换为字符串,然后返回。

否则,如果对象具有返回原始值的valueOf()方法,将这个原始值转换为字符串,然后返回。

否则,抛出异常

对象到数字的转换:

如果对象具有返回原始值的valueOf()方法,将这个原始值转换为数字,然后返回。

否则,如果对象具有返回原始值的toString()方法,将这个原始值转换为数字,然后返回。

否则,抛出异常

对象到原始值:

日期类:toString()

非日期类:先valueOf(),再toString()

+ 关系运算符:对象转换为原始值,字符串转换为原始值。

变量声明

重复的声明和遗漏的声明:至少使用var声明一次。

变量作用域

函数作用域和声明提前

函数作用域:局部变量在整个函数体始终是有定义的,甚至在变量声明之前。

作为属性的变量

作用域链

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: