JavaScript 使用技巧(持续更新)
类型检测
使用Object.prototype.toString.call(obj)的方式。
因为无论typeof还是instanceof都无法做到精确判断变量类型。
从数组中获取一个随机项
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];
在特定范围内获取一个随机数
var x = Math.floor(Math.random() * (max - min + 1)) + min;
将arguments对象转换成一个数组
var argArray = Array.prototype.slice.call(arguments);
获取一个数字数组中的最大值或最小值
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
清空一个数组
var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].
四舍五入一个数字,保留N位小数
var num =2.443242342;
num = num.toFixed(4); // num will be equal to 2.4432
使用for-in遍历一个对象内部属性的时候注意检查属性
for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}
缓存需要计算和查询(calculation or querying)的变量
对于jQuery选择器,我们最好缓存这些DOM元素。
var navright = document.querySelector('#right');
var navleft = document.querySelector('#left');
var navup = document.querySelector('#up');
var navdown = document.querySelector('#down');