javascript笔记

基本类型

type的基本常识

数字, 字符串, boolean, null, undefined是js的基本类型,它们不是object, 其 它所有的值都是object, 数字, 字符串, bookean这三种类型有对应的包装对象 (wrapper object),当你访问字符串的方法时,实际上会自动的创建一个临时的 字符串包装对象,就像调用了new String(s),当调用完成后这个临时对象会被丢弃, 对于数字(Number),bool(Boolean)都是同样的原理
数字,字符串,bool都是不可变的,而object是可变的.
类型转换: 2 + ‘2a’ = ‘22a’(操作符是+,则自动将数字转换为字符串,如果是其 它操作符则尝试将字符串转为整数,’22’转换为22, 但’2a’无法转换,这一点和 parseInt不同)
数字

不区分整数与浮点数

var x = 2;
var x = 2.22;
有一些数学函数,用来处理数字:

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
日期

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
字符串

字符串使用单引号或者双引号,建议使用单引号,因为这样可以更好的和html配合

var x = ‘hello world’; // 字符串单双引号等价
var x = “hello world”;
js的字符串实际上就是一串16位(2个字节)的值,因为js使用UTF-16来encoding unicode字符,所以如果一个uncode point使用utf-16编码后有3个字节,那么使用length时该字符就是2个长度,js的字符串操作基本都是以16位的值为基础, 而不是以逻辑上的字符为基础的

常见字符串处理函数

var s = “hello, world” // => 3: position of first “l” at or after 3
s.length // 12, the length of string(this is property, not method)

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 1.
s.lastIndexOf(“l”) // => 10: position of last letter 1.
s.indexOf(“l”, 3) // => 3: position of first “l” at or after 3

s.split(“, “) // [‘hello’, ‘world’] an Array
s.replace(“h”, “H”) // Hello world, replace all instances
s.toUpperCase() // HELLO WORLD
bool

只能为true或者false,以下的值会自动转换为false:

false
null
undefined
“” (empty string)
NAN (not a number)
0, -0
除以上的值之外的所有的值,包括所有的对象都会自动转换为true, 可以通过 !! 来明 确的将一个值转换为bool

undefined与null

前者表示没有定义,后者表示变量的值为空,eg:var x;(x为undefined)

正则表达式

Create RegExp Object

正则表示式是对象(RegExp对象), 有两种定义方法:

var pattern = /../;, 无引号,不是字符串.
var pattern = new RegExp(…);
正则表达式要写成一行, 因为正则表达式中空格是非常重要的.

flags

正则表达式可以指定标志, 比如 /../g, /../i.

g : 全局模式
i : 忽略大小写模式
group

正则表达式可以分组. 分组有以下几类:

(..) : 这种分组是捕获型分组, 每一个捕获型分组都会有一个编号, 这种编号是从 1开始, 如果一个捕获型分组的编号是 2, 且最后的结果是 result, 那么该分 组匹配的文本就是 result[2].
(?: ..): 以 ?: 开头, 非捕获型分组, 这种分组不会干扰捕获型分组的编号, 它 匹配的文本也不会出现在最终的结果中.
RegExp method

这是regexp的方法

.exec(str): 返回一个数组, 数组的第一个元素是匹配的完整字符串,接下来的元素 是所有的捕获型分组, 注意全局模式对exec不起作用, 它只返回第一个匹配.
.test(str): 如果str中包含能被匹配的字符串, 那么返回true, 否则返回false.
String method

这是字符串的方法

.search(regexp): 返回匹配字符串的第一个字符在原字符串中的index, 无匹配 那么返回 -1, 全局模式对search无用.

var s = “JavaScript is fun”;
s.search(/script/i) // Returns 4
s.search(/a(.)a/) // Returns 1
如果 search 的第一个参数不是正则表达式及而是一个字符串, 那么先将它转换 为正则表达式(将字符串传递给 new RegExp(..))

.replace(regexp, new_str): 返回替换后的新字符串, 如果regexp是全局模式, 那么会替换所有的匹配的字符串, 否则只替换第一处. 如果regexp中使用了分组,那 么可以在new_str中通过 $1, $2 … $n 来引用第一个, 第二个一直到第n个分组匹 配的字符串.

text.replace(/javascript/i, “JavaScript”);
“Doe, John”.replace(/(\w+)\s,\s(\w+)/, “$2 $1”); // => “John Doe”
如果 replace 的第一个参数不是正则表达式及而是一个字符串, 那么直接使用字 符串字面值匹配

.match(regexp): 返回一个数组, 如果regexp是全局模式, 那么数组元素就是所 有匹配的字符串, 如果没有使用全局模式, 那么数组的第一个元素是匹配的字符串, 接下来的元素是所有的捕获型分组, 具体可以看下面的例子.

// regexp has ‘g’ attribute
“1 plus 2 equals 3”.match(/\d+/g) // => [“1”, “2”, “3”]

// regexp doesn’t have ‘g’ attribute
var url = /(\w+):\/\/([\w.]+)\/(\S*)/;
var text = “Visit my home page at http://www.isp.com/~david“;
var result = text.match(url);
if (result != null) {
var fullurl = result[0]; // Contains “http://www.isp.com/~david
var protocol = result[1]; // Contains “http”
var host = result[2]; // Contains “www.isp.com”
var path = result[3]; // Contains “~david”
}
如果 match 的参数不是正则表达式, 那么先转换为正则表达式.

.split(regexp):
“123,456,789”.split(“,”); // => [‘123’, ‘456’, ‘789’]
“1, 2, 3, 4, 5”.split(/\s,\s/); // => [“1”,”2”,”3”,”4”,”5”]
不会将字符串字面值转换为正则表达式, 和 replace 类似.

Array

定义

定义数组可以使用两种方法: Array与[],但是推荐[],因为像 new Array(3)这样的代 码,它会返回一个空数组,可是却将这个数组的length设置为3,这是一个令人困惑的 特性

[1, 2, 3]; // 结果: [1, 2, 3]
new Array(1, 2, 3); // 结果: [1, 2, 3]

[3]; // 结果: [3]
new Array(3); // 结果: []
new Array(‘3’) // 结果: [‘3’]

// 译者注:因此下面的代码将会使人很迷惑
new Array(3, 4, 5); // 结果: [3, 4, 5]
new Array(3) // 结果: [],此数组长度为 3
遍历数组

不要使用for…in, 而要使用如下代码:

var list = [1, 2, 3, 4, 5, …… 100000000];
for(var i = 0, l = list.length; i < l; i++) {
console.log(list[i]);
}
原因是for … in会遍历整个原型链,效率不高

数组方法