使用!!操作符转换布尔值
对于变量可以使用!!variable做检测,只要变量的值为:0、null、””、undefined或者NaN都将返回的是false,反之返回的是true。
使用+将字符串转换成数字
1 2 3 4
| function toNumber(strNumber) { return +strNumber; } console.log(toNumber("1234")); // 1234
|
并条件符
使用||运算符
1 2 3 4
| function User(name, age) { this.name = name || "Oliver Queen"; this.age = age || 27; }
|
在循环中缓存array.length
1 2 3
| for(var i = 0, length = array.length; i < length; i++) { console.log(array[i]); }
|
检测对象中属性
1 2 3 4 5
| if ('querySelector' in document) { document.querySelector("#id"); } else { document.getElementById("id"); }
|
获取数组中最后一个元素
1 2 3
| var array = [1,2,3,4,5,6]; console.log(array.slice(-1)); // [6] console.log(array.slice(-2)); // [5,6]
|
数组截断
1 2 3 4 5
| var array = [1,2,3,4,5,6]; console.log(array.length); // 6 array.length = 3; console.log(array.length); // 3 console.log(array); // [1,2,3]
|
替换所有
1 2 3
| var string = "john john"; console.log(string.replace(/hn/, "ana")); // "joana john" console.log(string.replace(/hn/g, "ana")); // "joana joana"
|
合并数组
1 2 3
| var array1 = [1,2,3]; var array2 = [4,5,6]; console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];
|
将NodeList转换成数组
1 2 3
| var elements = document.querySelectorAll("p"); // NodeList var arrayElements = [].slice.call(elements); // Now the NodeList is an array var arrayElements = Array.from(elements); // This is another way of converting NodeList to Array
|
数组元素的洗牌
1 2
| var list = [1,2,3]; console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]
|