Javascript小技巧

获取整数

const a = '3.24' const b = '-3.24' const c = 3.24 const d = -3.24 // | 0:取整数部分 console.log(a | 0) // 3 console.log(b | 0) // -3 console.log(c | 0) // 3 console.log(d | 0) // -3 // ^ 0:取整数部分 console.log(a ^ 0) // 3 console.log(b ^ 0) // -3 console.log(c ^ 0) // 3 console.log(d ^ 0) // -3 // ~~:取整数部分 console.log(~~a) // 3 console.log(~~b) // -3 console.log(~~c) // 3 console.log(~~d) // -3 // parseInt:取整数部分 console.log(parseInt(a)) // 3 console.log(parseInt(b)) // -3 console.log(parseInt(c)) // 3 console.log(parseInt(d)) // -3 // Math.floor:向下取整 console.log(Math.floor(a)) // 3 console.log(Math.floor(b)) // -4 console.log(Math.floor(c)) // 3 console.log(Math.floor(d)) // -4 // Math.ceil:向上取整 console.log(Math.ceil(a)) // 4 console.log(Math.ceil(b)) // -3 console.log(Math.ceil(c)) // 4 console.log(Math.ceil(d)) // -3 // Math.round:四舍五入 console.log(Math.round(a)) // 4 console.log(Math.round(b)) // -4 console.log(Math.round(c)) // 3 console.log(Math.round(d)) // -3

获取Number型

const a = '3.24' // + console.log(+a) // 3.24 console.log(+ new Date()) // 1607950570132 console.log(+'123') // 123 console.log(+ {}) // NaN // Number console.log(Number(a)) // 3.24 // parseFloat console.log(parseFloat(a))// 3.24

保留指定小数位数

// 保留指定的小数位数 var num = 2.443242342 // toFixed 返回的是字符串(四舍五入),使用 + 返回 Number num = +num.toFixed(4) console.log(num, typeof num) // 2.4432

获取最大值,最小值

const numbers = [5, 0, 120, -215, 228, 11233205, -75411] const maxInNumbers = Math.max.apply(Math, numbers) // 得到数组中的最大值 const minInNumbers = Math.min.apply(Math, numbers) // 得到数组中的最小值 console.log(maxInNumbers) console.log(minInNumbers)

用0补全位数

生成一个字符串,用0补全位数

// 10^length function prefixInteger(num, length) { return (num / Math.pow(10, length)).toFixed(length).substr(2); } const str = prefixInteger(33, 6) console.log(str, typeof str) // 另一种方式 function prefixInteger1(num, length) { const str = (Array(length).fill(0).join('') + num) // slice使用负数,从末尾开始算起 return str.slice(-length) } const str1 = prefixInteger1(33, 6) console.log(str1, typeof str1)

生成随机字符串

// 生成随机的字母数字字符串 function generateRandomAlphaNum(len) { let str = '' for(; str.length < len; str += Math.random().toString(36).substr(2)); return str.substr(0, len) } console.log(generateRandomAlphaNum(10))

true & false

// true if (true) if ({}) if ([]) if (42) if ("foo") if (new Date()) if (-42) if (3.14) if (-3.14) if (Infinity) if (-Infinity) // false if (false) if (null) if (undefined) if (0) if (NaN) if ('') if ("") if (document.all)

类数组转数组

const arr = [].slice.call(arguments) const arr1 = Array.prototype.slice.call(arguments) const arr2 = Array.from(arguments)

打乱列表

// 利用sort方法快速排序的时候引入一个随机量 const list = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411] const shuffle = arr => arr.sort(() => Math.random() - 0.5) console.log(shuffle(list))

真正的洗牌函数参考:原生JS常用方法汇总 - 洗牌函数

switch、case

// 另类用法 function getCategory(age) { var category = "" switch (true) { case isNaN(age): category = "not an age" break case (age >= 50): category = "Old" break case (age <= 20): category = "Baby" break default: category = "Young" break } return category } console.log(getCategory()) // not an age console.log(getCategory(5)) // Baby console.log(getCategory(30)) // Young console.log(getCategory(55)) // Old // 字典的键值对取代switch语句 // 使用字典取代switch和if else语句也是函数式编程的理念之一. const day = 'Monday' ({ 'Monday': () => {}, 'Wednesday': () => {}, 'Friday': () => {}, 'default': () => {}, })[ day || 'default' ]

鼠标滚轮实现图片缩放方法

<!-- html代码 --> <img src="/images/picture.jpg" onmousewheel="return zoomImg(this)">
// js代码 function zoomImg(obj){ let zoom = parseInt(obj.style.zoom, 10) || 100 zoom += event.wheelDelta / 12 if (zoom > 0) { obj.style.zoom = zoom + '%' } return false }

备注

常用方法参考:原生JS常用方法汇总


创作不易,若本文对你有帮助,欢迎打赏支持作者!

 分享给好友: