~~x
对 x 取整最快的方法,其他方法x ^ 0
x << 0
a ^= b, b ^= a, a ^= b;
不引入变量情况下交换两个变量值最快的方法!!x
等同于Boolean(x)
i && doSomething();
等同于if (i) { doSomething(); }
function saveText(text) { text = text || ''; }
或运算符常用于为一个变量设置默认值-1 >>> 0 // 4294967295
上面代码表示,-1作为32位整数时,内部的储存形式使用无符号整数格式解读,值为4294967295(即(2^32)-1,等于11111111111111111111111111111111)<a href="http://example.com" onclick="f(); return false;">点击</a>
等同于<a href="javascript: void(f())">文字</a>
在超级链接中插入代码防止网页跳转,<a href="javascript: void(document.form.submit())"> 提交 </a>
用户点击链接提交表单,但是不产生页面跳转var x = 0; var y = (x++, 10);
结果 x 为 1,y 为 10,逗号运算符的一个用途是,在返回一个值之前,进行一些辅助操作- Number() 和 parseInt()
// 数值:转换后还是原来的值
Number(324) // 324
// 字符串:如果可以被解析为数值,则转换为相应的数值
Number('324') // 324
// 字符串:如果不可以被解析为数值,返回 NaN
Number('324abc') // NaN
// 空字符串转为0
Number('') // 0
// 布尔值:true 转成 1,false 转成 0
Number(true) // 1
Number(false) // 0
// undefined:转成 NaN
Number(undefined) // NaN
// null:转成0
Number(null) // 0
Number函数将字符串转为数值,要比parseInt函数严格很多。基本上,只要有一个字符无法转成数值,整个字符串就会被转为NaN
parseInt('42 cats') // 42
Number('42 cats') // NaN
parseInt和Number函数都会自动过滤一个字符串前导和后缀的空格
parseInt('\t\v\r12.34\n') // 12
Number('\t\v\r12.34\n') // 12.34
Number方法的参数是对象时,将返回NaN,除非是包含单个数值的数组
Number({a: 1}) // NaN
Number([1, 2, 3]) // NaN
Number([5]) // 5
- String()
String(123) // "123"
String('abc') // "abc"
String(true) // "true"
String(undefined) // "undefined"
String(null) // "null"
String方法的参数如果是对象,返回一个类型字符串;如果是数组,返回该数组的字符串形式
String({a: 1}) // "[object Object]"
String([1, 2, 3]) // "1,2,3"
- Boolean()
Boolean(undefined) // false
Boolean(null) // false
Boolean(0) // false
Boolean(NaN) // false
Boolean('') // false
注意,所有对象(包括空对象)的转换结果都是true,甚至连false对应的布尔对象new Boolean(false)也是true
Boolean({}) // true
Boolean([]) // true
Boolean(new Boolean(false)) // true
- 自动转换为字符串
'5' + 1 // '51'
'5' + true // "5true"
'5' + false // "5false"
'5' + {} // "5[object Object]"
'5' + [] // "5"
'5' + function (){} // "5function (){}"
'5' + undefined // "5undefined"
'5' + null // "5null"
- 自动转换为数值
除了加法运算符(+)有可能把运算子转为字符串,其他运算符都会把运算子自动转成数值。null 转为数值时为 0,而 undefined 转为数值时为 NaN
'5' - '2' // 3
'5' * '2' // 10
true - 1 // 0
false - 1 // -1
'1' - 1 // 0
'5' * [] // 0
false / '5' // 0
'abc' - 1 // NaN
null + 1 // 1
undefined + 1 // NaN
一元运算符也会把运算子转成数值
+'abc' // NaN
-'abc' // NaN
+true // 1
-false // 0