8.javascript常用方法

106 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第8天,点击查看活动详情

1.使用Array.prototype.at()简化arr.length

Array.prototype.at()接收一个正整数或者负整数作为参数,表示获取指定位置的成员

参数正数就表示顺数第几个,负数表示倒数第几个,这可以很方便的某个数组末尾的元素

var arr = [1, 2, 3]
// 以前
console.log(arr[arr.length-1]) // 3
// 简化后
console.log(arr.at(-1)) // 3

2.使用String.prototype.replaceAll()简化replace一次性替换所有子字符串

String.prototype.replaceAll()用法与String.prototype.replace()类似

但是replace仅替换第一次出现的子字符串,而replaceAll会替换所有

// 以前
console.log('aaa'.replace(/a/g,'b')) //bbb

// 简化后
console.log('aaa'.replaceAll('a','b')) //bbb

3.解构一个嵌套多层的对象中某些属性

let obj = {
  part1: {
    name: '一',
    age: 23
  }
}
const { part1: { name, age }, part1 } = obj
console.log(part1,name, age)   // {name: "一", age: 23}  一  23

4.一行代码生成随机字符串,数量自定义

const hash = (num,str) => (strValue = (str || '') + Math.random().toString(32).slice(2)) && !num?strValue:((deffNum = strValue.length - num),(deffNum >= 0?  strValue.slice(0,strValue.length - deffNum): hash(num,strValue)))
hash(20)

5.数字分隔符

有时你会在文件中定义一个数字常量

const money = 1000000000000

这么多个 0 ,1、2 ... 6、7 ... 数晕了都,怎么办?

const money = 1_000_000_000_000
console.log(money)  // 1000000000000

6.判断是否是json字符串

const isJson = str => {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
};
isJson('{"name":"小明"}'); // true
isJson('{"name:"小王"}'); // false
  • 截断字符串长度
  const splitStr= (string, length) => string.length < length ? string : `${string.slice(0, length)}...`;
  splitStr('Hello World', 7)  // Hello W...
  splitStr('Hello World', 10) // Hello Worl...

7.一行代码生产非空的数组

const createdArray = (num, value) => num?(value?new Array(num).fill(value):new Array(num).fill(0).map((_,i)=>i)):new Array()

image.png

8.RGB与十六进制转换

RGB转十六进制

const rgbToHex = (color) => values = color.replace(/rgb?\(/, '').replace(/\)/, '').replace(/[\s+]/g, '').split(',') && "#" + ((1 << 24) + (parseInt(values[0]) << 16) + (parseInt(values[1]) << 8) + parseInt(values[2])).toString(16).slice(1)
rgbToHex('rgb(248,201,196)'); // #f8c9c4

十六进制转RGB

const hexToRgb = (color) => 'rgb(' + parseInt('0x' + color.slice(1, 3)) + ',' + parseInt('0x' + color.slice(3, 5)) + ',' + parseInt('0x' + color.slice(5, 7)) + ')';
hexToRgb('#f8c9c4') // rgb(248,201,196)

rgba转十六进制

const rgbaToHex = (color) => { // 传的color须为字符串
  var values = color
    .replace(/rgba?\(/, '')  // 把 "rgba(" 去掉,变成  "194, 7, 15, 1)"
    .replace(/\)/, '')		 // 把 ")" 去掉,变成 "194, 7, 15, 1"
    .replace(/[\s+]/g, '')   // 把空格去掉,变成 "194,7,15,1"
    .split(',')				 // 变成数组 [194,7,15,1]
  var a = parseFloat(values[3] || 1), // values[3]是rgba中的a值,没有的话设置a为1,a可能为小数,所以用parseFloat函数
    r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),  // 转换为16进制
    g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
    b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255)
  return '#' +
    ('0' + r.toString(16)).slice(-2) + // 转换后的16进制可能为一位,比如 7 就转换为 7 , 15 转换为 f
    ('0' + g.toString(16)).slice(-2) + // 当为一位的时候就在前面加个 0,
    ('0' + b.toString(16)).slice(-2) // 若是为两位,加 0 后就变成了三位,所以要用 slice(-2) 截取后两位
}
rgbaToHex('rgba(241,148,138,0.5)') // #f8c9c4