15 种你可能从未听说过的杀手🗡 JS 技术🔈🔥让我们来谈谈👋

2025-05-24

你可能从未听说过的 15 种杀手级 JS 技术🔈🔥

我们来聊聊👋

我们都同意,在 Google 或 StackOverflow 上搜索 Javascript 错误修复或答案并不好玩🏴‍☠️。

这里有二十种简短而强大的 JavaScript 技术,可以最大限度地提高生产力⚡️并最大限度地减少痛苦🩸。

让我们深入研究代码🤘

唯一数组

从数组中过滤掉重复的值。

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

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

解释
MDN 参考

唯一的对象数组

由于每个对象都是不同的,因此该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);
Enter fullscreen mode Exit fullscreen mode

请参阅此评论中的更有效但稍长的方法

解释
MDN 参考

Stackoverflow 解决方案


数组迭代器索引

使用.map.forEachjavascript 迭代函数,您可以获取每个项目的索引。

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

解释
Array.prototype.map(MDN)

Array.prototype.forEach(MDN)


按字符数拆分字符串

我们可以使用.match正则表达式函数按字符拆分字符串n

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

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

解释
在我们使用的正则表达式中/.{1,2}/g,数字2代表要拆分的字符数。如果有余数,此方法仍然有效。

或者,如果您想按n字符拆分字符串(其中n可能会发生变化),则可以使用new RegExp

const splitPairsBy = (n) => str.match(new RegExp(`.{1,${n}}`, "g"))
Enter fullscreen mode Exit fullscreen mode

字符串.prototype.match(MDN)

Stackoverflow 解决方案


按不同字符拆分字符串

另一个正则表达式技巧.match允许您将“aabbc”之类的字符串拆分为一个数组["aa", "bb", "c"]

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

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

解释
字符串.prototype.match(MDN)

Stackoverflow 解决方案


遍历对象

Object.entries允许我们将 JSON 对象转换为键值对数组,从而使我们能够使用循环或数组迭代器对其进行迭代。

const obj = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
};
const iteratedObject = Object.entries(obj)
  .map(([key, value]) => `${key} = ${value}`);

console.log(iteratedObject); // ['key1 = value1', 'key2 = value2', 'key3 = value3']
Enter fullscreen mode Exit fullscreen mode

解释
如果obj通过Object.entries,它看起来会像这样:
[
  ["key1", "value1"],
  ["key2", "value2"],
  ["key3", "value3"]
]
Enter fullscreen mode Exit fullscreen mode

结合使用.map函数和对象解构,我们可以访问键值。

Object.entries(MDN)


键值数组转对象

您可以Object.entryified使用以下方式将“ ”键值数组转换回对象Object.fromEntries

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

const originalObject = Object.fromEntries(entryified);

console.log(originalObject); // { key1: 'value1', ... }
Enter fullscreen mode Exit fullscreen mode

解释
Object.fromEntries(MDN)

发生计数

你可能想计算某个元素在数组中出现的次数。我们可以将.filter函数与迭代器结合使用来实现。

const occurrences = ["a", "b", "c", "c", "d", "a", "a", "e", "f", "e", "f", "g", "f", "f", "f"];
// creating a unique array to avoid counting the same char more than once
const unique = Array.from(new Set(occurrences));

const occurrenceCount = Object.fromEntries(
  unique.map(char => {
    const occurrenceCount = occurrences.filter(c => c === char).length;
    return [char, occurrenceCount]
  })
)

console.log(occurrenceCount); // { a: 3, b: 1, c: 2, ... }
Enter fullscreen mode Exit fullscreen mode

请查看此评论中的可靠单行代码来执行此操作

解释
数组.prototype.filter (MDN)

替换回调

.replace函数并不局限于只能用固定字符串进行替换。你可以将回调传递给它,并使用匹配的子字符串。

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
Enter fullscreen mode Exit fullscreen mode

解释
String.prototype.replace(MDN)

条件链

你们中的许多人都熟悉在 JS 中遇到未定义错误的情况,条件链可以防止很多此类错误的发生。

可选链式调用( )?.运算符用于访问对象的属性或调用函数。如果使用此运算符访问的对象或调用的函数为 undefined 或 null,则表达式将短路并计算结果为 undefined,而不是抛出错误。

const obj = {
  "a": "aaaaaaa",
  "b": null
};

console.log(obj.b.d); // throws an error

console.log(obj.b?.d); // returns undefined
Enter fullscreen mode Exit fullscreen mode

解释
可选链式调用(MDN)

限制数字

你经常需要将数字限制在某个范围内。每次都需要用三元运算符来做这件事很麻烦。用函数会干净得多。

const constrain = (num, min, max) => {
  if(num < min) return min;
  else if(num > max) return max;
  else return num;
}

constrain(5, 1, 3) // 3
constrain(2, 1, 5) // 2
constrain(0, -100, 100) // 0
Enter fullscreen mode Exit fullscreen mode

更好的方法是使用Math.min如下Math.max方法:

const constrain = (num, min, max) => Math.min(Math.max(num, min), max)
Enter fullscreen mode Exit fullscreen mode

谢谢@ jonrandy🙏

解释
If-else(MDN)🤪

索引数组的前面和后面

.at函数允许您使用正数和负数从头到尾对数组进行索引。

const arr = [1, 2, 3, 4, 5];

arr.at(0) // 1
arr.at(1) // 2
arr.at(-1) // 5
arr.at(-2) // 4
Enter fullscreen mode Exit fullscreen mode

解释
Array.prototype.at (MDN)

按字母顺序排序

按字母顺序对字符串数组进行排序

const words = ["javascript", "typescript", "python", "ruby", "swift", "go", "clojure"];
const sorted = words.sort((a, b) => a.localeCompare(b));

console.log(sorted); // ['clojure', 'go', 'javascript', 'python', 'ruby', 'swift', 'typescript']
Enter fullscreen mode Exit fullscreen mode

💡提示a.localeCompare(b):您可以通过切换到来切换升序和降序b.localeCompare(a)

解释
Array.prototype.sort(MDN)

按真值/假值排序

您可以根据真值/假值对数组进行排序,将真值放在最前面,将假值放在后面。

const users = [
  { "name": "john", "subscribed": false },
  { "name": "jane", "subscribed": true },
  { "name": "jean", "subscribed": false },
  { "name": "george", "subscribed": true },
  { "name": "jelly", "subscribed": true },
  { "name": "john", "subscribed": false }
];

const subscribedUsersFirst = users.sort((a, b) => Number(b.subscribed) - Number(a.subscribed))
Enter fullscreen mode Exit fullscreen mode

Number(false)等于零,Number(true)等于一。这就是我们可以将其传递给 sort 函数的方法。

解释
Array.prototype.sort(MDN)

号码 (MDN)


将小数四舍五入为n数字

您可以使用 将小数四舍五入为n数字.toFixed。请注意,.toFixed会将数字转换为字符串,因此我们必须将其重新解析为数字。

console.log(Math.PI); // 3.141592653589793
console.log(Number(Math.PI.toFixed(2)))
Enter fullscreen mode Exit fullscreen mode

解释
Number.prototype.toFixed (MDN)


感谢阅读✨!

我乐于接受反馈。如果您有任何想法或意见,请在下方评论区分享。

我们来聊聊👋

文章来源:https://dev.to/ironcladdev/15-killer-js-techniques-youve-probously-never-heard-of-1lgp
PREV
我用来将网站访问量提升至每月 2 万以上的 SEO 工具
NEXT
2020 年 3 月和 4 月(隔离期间)GitHub 上最受欢迎的 51 个 JS 存储库