单行JS代码实现生成随机字符串、转义HTML特殊字符、将字符串中每个单词的第一个字符大写、将字符串转换为camelCase、删除数组中的重复值、展平一个数组、从数组中删除虚假值、检查一个数字是偶数还是

1、生成随机字符串

我们可以使用 Math.random 生成一个随机字符串,当我们需要一个唯一的 ID 时非常方便。

const randomString = () => Math.random().toString(36).slice(2)randomString() // gi1qtdego0brandomString() // f3qixv40motrandomString() // eeelv1pm3ja

2、转义HTML特殊字符

如果您了解 XSS,其中一种解决方案是转义 HTML 字符串。

const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m]))escape('<div class="medium">Hi Medium.</div>') // &lt;div class=&quot;medium&quot;&gt;Hi Medium.&lt;/div&gt

3、将字符串中每个单词的第一个字符大写

此方法用于将字符串中每个单词的第一个字符大写。

const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())uppercaseWords('hello world'); // 'Hello World'

4、将字符串转换为camelCase​​​​​​​

const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));toCamelCase('background-color'); // backgroundColortoCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumbtoCamelCase('_hello_world'); // HelloWorldtoCamelCase('hello_world'); // helloWorld

5、删除数组中的重复值

删除数组的重复项是非常有必要的,使用“Set”会变得非常简单。​​​​​​​

const removeDuplicates = (arr) => [...new Set(arr)]console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6])) // [1, 2, 3, 4, 5, 6]

6、 展平一个数组

我们经常在面试中受到考验,这可以通过两种方式来实现。​​​​​​​

const flat = (arr) =>    [].concat.apply(        [],        arr.map((a) => (Array.isArray(a) ? flat(a) : a))    )// Orconst flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']

7、从数组中删除虚假值

使用此方法,您将能够过滤掉数组中的所有虚假值。​​​​​​​

const removeFalsy = (arr) => arr.filter(Boolean)removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])// ['a string', true, 5, 'another string']

8、检查一个数字是偶数还是奇数

超级简单的任务,可以通过使用模运算符 (%) 来解决。​​​​​​​

const isEven = num => num % 2 === 0isEven(2) // trueisEven(1) // false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值