你可能从未听说过的 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']
唯一的对象数组
由于每个对象都是不同的,因此该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);
请参阅此评论中的更有效但稍长的方法。
数组迭代器索引
使用.map
和.forEach
javascript 迭代函数,您可以获取每个项目的索引。
const arr = ['a', 'b', 'c'];
const letterPositions = arr.map(
(char, index) => `${char} is at index ${index}`
)
按字符数拆分字符串
我们可以使用.match
正则表达式函数按字符拆分字符串n
。
const str = "asdfghjklmnopq";
const splitPairs = str.match(/.{1,2}/g);
console.log(splitPairs); // ['as', 'df', 'gh', 'jk', 'lm', 'no', 'pq']
解释
在我们使用的正则表达式中
/.{1,2}/g
,数字2
代表要拆分的字符数。如果有余数,此方法仍然有效。
或者,如果您想按n
字符拆分字符串(其中n
可能会发生变化),则可以使用new RegExp
。
const splitPairsBy = (n) => str.match(new RegExp(`.{1,${n}}`, "g"))
按不同字符拆分字符串
另一个正则表达式技巧.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']
遍历对象
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']
解释
如果
obj
通过Object.entries
,它看起来会像这样:
[
["key1", "value1"],
["key2", "value2"],
["key3", "value3"]
]
结合使用.map
函数和对象解构,我们可以访问键值。
键值数组转对象
您可以Object.entryified
使用以下方式将“ ”键值数组转换回对象Object.fromEntries
const entryified = [
["key1", "value1"],
["key2", "value2"],
["key3", "value3"]
];
const originalObject = Object.fromEntries(entryified);
console.log(originalObject); // { key1: 'value1', ... }
发生计数
你可能想计算某个元素在数组中出现的次数。我们可以将.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, ... }
请查看此评论中的可靠单行代码来执行此操作!
替换回调
该.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
条件链
你们中的许多人都熟悉在 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
限制数字
你经常需要将数字限制在某个范围内。每次都需要用三元运算符来做这件事很麻烦。用函数会干净得多。
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
更好的方法是使用Math.min
如下Math.max
方法:
const constrain = (num, min, max) => Math.min(Math.max(num, min), max)
谢谢@ jonrandy🙏
索引数组的前面和后面
该.at
函数允许您使用正数和负数从头到尾对数组进行索引。
const arr = [1, 2, 3, 4, 5];
arr.at(0) // 1
arr.at(1) // 2
arr.at(-1) // 5
arr.at(-2) // 4
按字母顺序排序
按字母顺序对字符串数组进行排序
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']
💡提示a.localeCompare(b)
:您可以通过切换到来切换升序和降序b.localeCompare(a)
按真值/假值排序
您可以根据真值/假值对数组进行排序,将真值放在最前面,将假值放在后面。
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))
Number(false)
等于零,Number(true)
等于一。这就是我们可以将其传递给 sort 函数的方法。
将小数四舍五入为n
数字
您可以使用 将小数四舍五入为n
数字.toFixed
。请注意,.toFixed
会将数字转换为字符串,因此我们必须将其重新解析为数字。
console.log(Math.PI); // 3.141592653589793
console.log(Number(Math.PI.toFixed(2)))
感谢阅读✨!
我乐于接受反馈。如果您有任何想法或意见,请在下方评论区分享。