一. 实用小技巧
(1)对小数取整
常规的对小数取整的方法有parseInt(1.2),Math.floor(1.2), Math.ceil(-1.2), Math.round(1.6)
新学的方法:
1 | var a = 3.2; |
(2)精确到某一位小数
1 | 2.345.toFixed(2) |
缺点:结果会变成字符串类型
(3)两个!!可以快速转换为bool型数据
undefined, null, 0, false, NaN, ‘ ‘
这些数据前面加上!!都会转换为false
(4)~按位取反: 可以理解为取反之后再减1
1 | var a = 'abc'; |
1 | var a = 1, b = -1, c = 0, d = 3, e = -3; |
二. 常用工具函数
1.以下JS函数用于获取url参数:
1 | function getQueryVariable(variable) |
使用:
1 | url实例:http://www.runoob.com/index.php?id=1&image=awesome.jpg |
简易版节流函数:前面的如果没有结束,本次绑定就不生效。
1
2
3
4
5
6
7
8
9
10
11function throttle (delay, action) {
var last = 0;
return function () {
var current = +new Date();
if (current - last > delay) {
// action.apply(this, arguments);
action(arguments);
last = current;
}
}
}简易版防抖函数:让前面的绑定失效,从这次开始计时。
1 | function debounce (idle, action) { |