提升javascript效率的代码

  • 声明未赋值 / 未声明的变量 typeof x == “undefined”
	(() => {
  		let x = (y = 10);
	})();
	console.log(typeof x); // "undefined"
	console.log(typeof y); // "number"
  • 当map函数没有返回任何值时,即默认返回undefined.对数组中的每一个元素来说,函数块都得到了这个返回值,所以结果中每一个元素都是undefined.
	[1, 2, 3].map(num => {
 	 	if (typeof num === "number") return;xx
 	 	return num * 2;
	});
  • const num = parseInt(“7*6”, 10);
    =>
    parseInt 检查字符串中的字符是否合法. 一旦遇到一个在指定进制中不合法的字符后,立即停止解析并且忽略后面所有的字符。
    num=7

  • object的key值只有string和symbol型,其他类型会隐式转换为string类型,所以a[b]和a[c]其实都等价于a[object],所以456会覆盖123

    const a = {}
    const b = { key: 'b' }
    const c = { key: 'c' }
    a[b] = 123
    a[c] = 456
    console.log(a[b]) // 456
    
  • 基本类型通过它们的值(value)进行比较,而对象通过它们的引用(reference)进行比较

    function checkAge(data) {
      if (data === { age: 18 }) {
        console.log('You are an adult!')
      } else if (data == { age: 18 }) {
        console.log('You are still an adult.')
      } else {
        console.log(`Hmm.. You don't have an age I guess`)
      }
    }
    checkAge({ age: 18 })
    => "Hmm.. You don't have an age I guess"
    
  • 如果使用标记模板字面量,第一个参数的值总是包含字符串的数组。其余的参数获取的是传递的表达式的值!

    function getPersonInfo(one, two, three) {
      console.log(one)
      console.log(two)
      console.log(three)
    }
    const person = 'Lydia'
    const age = 21
    getPersonInfo`${person} is ${age} years old`
    => ["", " is ", " years old"] "Lydia" 21
    
  • ReferenceError、SyntaxError、TypeError

    • ReferenceError:当对变量/项的引用被破坏或不存在时,将引发此错误。也就是说,当你尝试引用一个未被定义的变量时,将会抛出一个 ReferenceError 。
    • SyntaxError:Javascript引擎发现了不符合语法规范的代码,会出现此错误。解析期间,JS引擎捕获了此错误。
    • TypeError:TypeError 是指对象用来表示值的类型非预期类型时发生的错误。例如,我们期望它是布尔值,但结果发现它是string类型。
  • colorChange 是一个静态方法。静态方法被设计为只能被创建它们的构造器使用(也就是 Chameleon),并且不能传递给实例。因为 freddie 是一个实例,静态方法不能被实例使用

    class Chameleon {
      static colorChange(newColor) {
        this.newColor = newColor
        return this.newColor
      }
      constructor({ newColor = 'green' } = {}) {
        this.newColor = newColor
      }
    }
    const freddie = new Chameleon({ newColor: 'purple' })
    freddie.colorChange('orange')
    => TypeError
    
  • var b = 1;
    (function b(){
        b=2
        console.log(b)
    })()
    =>
    ƒ b(){
        b=2
        console.log(b)
    }
    
  • 数组拆解: flat: [1,[2,3]] --> [1, 2, 3]

Array.prototype.flat = function() {
    return this.toString().split(',').map(item => +item )
}
  • 生成随机字符串
    当我们需要一个唯一id时,通过Math.random创建一个随机字符串简直不要太方便噢!
const randomString = () => Math.random().toString(36).slice(2)
randomString() // gi1qtdego0b
randomString() // f3qixv40mot
randomString() // eeelv1pm3ja
  • 转义HTML特殊字符
    解决XSS方法之一就是转义HTML。
const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m]))
escape('<div class="medium">Hi Medium.</div>') 
// &lt;div class=&quot;medium&quot;&gt;Hi Medium.&lt;/div&gt
  • 单词首字母大写
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
uppercaseWords('hello world'); // 'Hello World'
  • 将字符串转换为小驼峰
const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
toCamelCase('background-color'); // backgroundColor
toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
toCamelCase('_hello_world'); // HelloWorld
toCamelCase('hello_world'); // helloWorld
  • 删除数组中的重复值
    得益于ES6,使用Set数据类型来对数组去重太方便了。
const removeDuplicates = (arr) => [...new Set(arr)]
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6])) 
// [1, 2, 3, 4, 5, 6]
  • 铺平一个数组
const flat = (arr) =>
    [].concat.apply(
        [],
        arr.map((a) => (Array.isArray(a) ? flat(a) : a))
    )
// Or
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])
flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']
  • 移除数组中的假值
const removeFalsy = (arr) => arr.filter(Boolean)
removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])
// ['a string', true, 5, 'another string']
  • 确认一个数字是奇数还是偶数
const isEven = num => num % 2 === 0
isEven(2) // true
isEven(1) // false
  • 获取两个数字之间的随机数
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 50) // 25
random(1, 50) // 34
  • 计算平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5);   // 3
  • 将数字截断到固定的小数点
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01
round(1.555, 2) //1.56
  • 计算两个日期之间天数
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date("2021-11-3"), new Date("2022-2-1"))  // 90
  • 从日期中获取是一年中的哪一天
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
dayOfYear(new Date()) // 74
  • 获取一个随机的颜色值
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`
randomColor() // #9dae4f
randomColor() // #6ef10e
  • 将RGB颜色转换为十六进制颜色值
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
rgbToHex(255, 255, 255)  // '#ffffff'
  • 清除所有的cookie
const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)))
  • 检测黑暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
  • 交换两个变量的值
[foo, bar] = [bar, foo]
  • 暂停一会
const pause = (millis) => new Promise(resolve => setTimeout(resolve, millis))
const fn = async () => {
  await pause(1000)
  console.log('fatfish') // 1s later
}
fn()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值