关于js的一些小技巧

整理自: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)}`
}
如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注