好用的JavaScript方法

81 阅读3分钟
Array.prototype.includes()

判断一个数组中是否包含指定的值,包含返回true,否则返回false

let arr = ['es6', 'es7', NaN, 'es8']
console.log(arr.includes(NaN)) // true
Object.values()

返回一个数组,成员是对象自身的可遍历属性的键值

let obj = {
    a: 1,
    b: 2,
    c: {
        a: 1,
        b: 2
    }
}
console.log(Object.values(obj)) // [1,2,{a:1,b:2}]
Object.keys()

返回一个数组,成员是对象自身的可遍历属性

let obj = {
    a: 1,
    b: 2,
    c: {
        a: 1,
        b: 2
    }
}
console.log(Object.keys(obj)) // ['a','b','c']
Object.entries()

方法返回一个数组,成员是对象自身的可遍历属性的键值对数组

let obj = {
    a: 1,
    b: 2,
    c: {
        a: 1,
        b: 2
    }
}
console.log(Object.entries(obj)) // [['a',1],['b',1],['c',{a: 1, b: 2}]]
Object.fromEntries()

把键值对列表转换为一个对象,这个方法是和 Object.entries() 相对的。

let obj = [['a',1],['b',1],['c',{a: 1, b: 2}]]
console.log(Object.fromEntries(obj)) // {a: 1,b: 2,c: {a: 1,b: 2}}

// 应用场景
// 1.map 转 object
const map = new Map()
map.set('a', 1)
map.set('b', 2)
console.log(map) // {'a' => 1, 'b' => 2}

const obj = Object.fromEntries(map)
console.log(obj) // {a: 1, b: 2}

// 2. 过滤大于10组成的对象
const list = {
    a: 13,
    b: 5,
    c: 9,
    d: 11
}
const res = Object.entries(list).filter(([key, val]) => val > 10)
console.log(res) // [ [ 'a', 13 ], [ 'd', 11 ] ]
console.log(Object.fromEntries(res)) // { a: 13, d: 11 }

String.prototype.padStart

把指定字符串填充到字符串头部,返回新字符串。

语法

str.padStart(targetLength [, padString])

- targetLength

当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。

- padString 可选

填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断。此参数的默认值为 " "

'a'.padStart(5);         // "    a"
'a'.padStart(5, "ABC");  // "ABCAa"
'a'.padStart(4,"123465"); // "123a"
'a'.padStart(3, "0");     // "00a"
'ab'.padStart(1);          // "ab"

// 应用场景
// 时间格式 yyyy-mm-dd
const now = new Date()
const year = now.getFullYear()
// 月份和日期 如果是一位前面给它填充一个0
const month = (now.getMonth() + 1).toString().padStart(2, '0')
const day = (now.getDate()).toString().padStart(2, '0')
console.log( `${year}-${month}-${day}` ) // 2023-07-21

// 手机号展示后4位
const tel = '18888888888'
const newTel = tel.slice(-4).padStart(tel.length, '*')
console.log(newTel) // *******8888
String.prototype.padEnd

把指定字符串填充到字符串尾部,返回新字符串。

语法同上

'a'.padEnd(5);      // "a    "
'a'.padEnd(5, "ABC");  // "aABCA"
'a'.padEnd(4, "123456"); // "a123"
'ab'.padEnd(1);      // "ab"
String.prototype.trimStart()
String.prototype.trimLeft()

删除字符串开头的空格

let str = '  str'
console.log(str, str.length)  //   str 5
str = str.trimStart()  // str = str.trimLeft()
console.log(str, str.length)  // str 3
String.prototype.trimEnd()
String.prototype.trimRight()

删除字符串结尾的空格

let str = 'str  '
console.log(str, str.length)  // str   5
str = str.trimEnd()  // str = str.trimRight()
console.log(str, str.length)  // str 3
String.prototype.trim()

删除字符串两端的空格

let str = '  str  '
console.log(str, str.length)  //   str   7
str = str.trim()
console.log(str, str.length)  // str 3
String.prototype.replaceAll()

replaceAll() 方法返回一个新字符串,其中所有匹配 pattern 的部分都被替换为 replacement。pattern 可以是一个字符串或一个 RegExp,replacement 可以是一个字符串或一个在每次匹配时调用的函数。原始字符串保持不变。

语法

replaceAll(pattern, replacement)

如果 pattern 是一个正则表达式,则必须设置全局(g)标志,否则会抛出 TypeError。

let str = 'abcdcdcd'
console.log('replace: ' + str.replace('c', '-')) // 'ab-dcdcd'
console.log('replaceAll: ' + str.replaceAll('c', '-')) // 'ab-d-d-d'

console.log('replace: ' + str.replace(/c/g, '-')) // 'ab-d-d-d'
console.log('replaceAll: ' + str.replaceAll(/c/g, '-')) // 'ab-d-d-d'