整理自:https://segmentfault.com/a/1190000015396476?utm_source=weekly&utm_medium=email&utm_campaign=email_weekly
去掉小数部分
const num = 1.256
Math.trunc(num) //ES6
parseInt(num)
~~num
num >> 0
num | 0
判断 x
是否是整数
function isInt (x) {
return (x ^ 0) === x
}
// return Math.round(x) === x
// return (typeof x === 'number') && (x % 1 === 0)
// ES6 -> Number.isInteger()
判断符号是否相同
function sameSign (a, b) {
return (a ^ b) >= 0
}
数组去重
// ES6
Array.from(new Set(arr))
// ES5
arr.filter(function (ele, index, array) {
return index === array.indexOf(ele)
})
或者使用reduce
arr.reduce((calculator, next) => {
if (calculator.indexOf(next) === -1) {
calculator.push(next)
}
return calculator
}, [])
产生随机颜色
function getRandomColor () {
return `#${Math.random().toString(16).substr(2, 6)}`
}
如果觉得我的文章对您有用,请您随意打赏。您的支持将鼓励我更加努力创作!
如无特殊声明,文章均为原创,若有不正之处,万望告知。转载请附上原文地址,十分感谢!