1、过滤掉数组中的重复值。

const arr = ["a", "b", "c", "d", "d", "c", "e"]
const uniqueArray = Array.from(new Set(arr));

console.log(uniqueArray); // ['a', 'b', 'c', 'd', 'e']

2、独特的对象数组技巧

Set对象不允许您过滤掉重复的对象,因为每个对象都不同。

JSON.stringify在这里对我们有用。

const arr = [{ key: 'value' }, { key2: 'value2' }, { key: 'value' }, { key3: 'value3' }];
const uniqueObjects = Array.from(
new Set(
arr.map(JSON.stringify)
)
).map(JSON.parse)

console.log(uniqueObjects);

3.数组迭代器索引技巧

使用.map.forEachjavascript迭代函数,你可以得到每个项目的索引

const arr = ['a', 'b', 'c'];
const letterPositions = arr.map(
(char, index) => `${char} is at index ${index}`
)

4.按字符数拆分字符串技巧

const str = "asdfghjklmnopq";
const splitPairs = str.match(/.{1,2}/g);

console.log(splitPairs); // ['as', 'df', 'gh', 'jk', 'lm', 'no', 'pq']

5.用不同的字符拆分字符串技巧

const str = "abbcccdeefghhiijklll";
const splitChars = str.match(/(.)\1*/g);

console.log(splitChars); // ['a', 'bb', 'ccc', 'd', 'ee', 'f', 'g', 'hh', 'ii', 'j', 'k', 'lll']

6.将键值数组转换成对象技巧

Object.entryified”键值数组转换回对象Object.fromEntries

const entryified = [
["key1", "value1"],
["key2", "value2"],
["key3", "value3"]
];

const originalObject = Object.fromEntries(entryified);

console.log(originalObject); // { key1: 'value1', ... }

7.回调替换技巧

const string = "a dog went to dig and dug a doggone large hole";
const replacedString = string.replace(/d.g/g, str => str + "gy")

console.log(replacedString); // a doggy went to diggy and duggy a doggygone large hole