、生成随机字符串
我们可以使用 Math.random 生成一个随机字符串,当我们需要一个唯一的 ID 时非常方便。
const randomString = () => Math.random().toString(36).slice(2)
randomString() // gi1qtdego0b
randomString() // f3qixv40mot
randomString() // eeelv1pm3ja
2、转义HTML特殊字符
如果您了解 XSS,其中一种解决方案是转义 HTML 字符串。
const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]))
escape('<div class="medium">Hi Medium.</div>')
// <div class="medium">Hi Medium.</div>
3、将字符串中每个单词的第一个字符大写
此方法用于将字符串中每个单词的第一个字符大写。
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
uppercaseWords('hello world'); // 'Hello World'
另外,在这里,我要谢谢克里斯托弗·斯特罗利亚-戴维斯,他还跟我分享了他的更加简单的方法,代码如下:
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
4、将字符串转换为camelCase
const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
toCamelCase('background-color'); // backgroundColor
toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
toCamelCase('_hello_world'); // HelloWorld
toCamelCase('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))
)
// Or
const 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 === 0
isEven(2) // true
isEven(1) // false
9、获取两个数字之间的随机整数
此方法用于获取两个数字之间的随机整数。
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 50) // 25
random(1, 50) // 34
10、获取参数的平均值
我们可以使用 reduce 方法来获取我们在此函数中提供的参数的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5); // 3
11、将数字截断为固定小数点
使用 Math.pow() 方法,可以将一个数字截断为我们在函数中提供的某个小数点。
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01
round(1.555, 2) //1.56
12、计算两个日期相差天数
有时候我们需要计算两个日期之间的天数,一行代码就可以搞定。
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date("2021-11-3"), new Date("2022-2-1")) // 90
13、从日期中获取一年中的哪一天
如果我们想知道某个日期是一年中的哪一天,我们只需要一行代码即可实现。
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
dayOfYear(new Date()) // 74
14、生成一个随机的十六进制颜色
如果你需要一个随机的颜色值,这个函数就可以了。
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`
randomColor() // #9dae4f
randomColor() // #6ef10e
15、将RGB颜色转换为十六进制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
rgbToHex(255, 255, 255) // '#ffffff'
16、清除所有cookies
const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)))
17、检测暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
18、交换两个变量
[foo, bar] = [bar, foo]
19、暂停一会
我们的日常开发工作中,文本溢出截断省略是很常见的一种需考虑的业务场景细节。看上去 “稀松平常” ,但在实现上却有不同的区分,是单行截断还是多行截断?多行的截断判断是基于行数还是基于高度?这些问题之下,都有哪些实现方案?他们之间的差异性和场景适应性又是如何?
一般来说,在做这样文字截断效果时我们更多是希望:
基于上述的准则,下面我们通过编码实践,给出一些答案。
核心 CSS 语句
优点
短板
适用场景
Demo
<div class="demo">
床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光
</div>
.demo {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
效果示例
核心 CSS 语句
优点
短板
适用场景
Demo
<div class="demo">
床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光
</div>
.demo {
display: -webkit-box;
overflow: hidden;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
效果示例
核心 CSS 语句
优点
短板
适用场景
Demo
<div class="demo">
床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光
</div>
.demo {
position: relative;
line-height: 18px;
height: 36px;
overflow: hidden;
word-break: break-all;
}
.demo::after {
content:"...";
font-weight:bold;
position:absolute;
bottom:0;
right:0;
padding:0 20px 1px 45px;
/* 为了展示效果更好 */
background: -webkit-gradient(linear, left top, right top, from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white));
background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
}
效果示例
核心 CSS 语句
优点
短板
适用场景
Demo
<div class="demo">
<div class="text">
床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光
</div>
</div>
.demo {
height: 40px;
line-height: 20px;
overflow: hidden;
}
.demo .text {
float: right;
margin-left: -5px;
width: 100%;
word-break: break-all;
}
.demo::before {
float: left;
width: 5px;
content: "";
height: 40px;
}
.demo::after {
float: right;
content: "...";
height: 20px;
line-height: 20px;
padding-right: 5px;
text-align: right;
width: 3em;
margin-left: -3em;
position: relative;
left: 100%;
top: -20px;
padding-right: 5px;
/* 为了展示效果更好 */
background: -webkit-gradient(
linear,
left top,
right top,
from(rgba(255, 255, 255, 0)),
to(white),
color-stop(50%, white)
);
background: -moz-linear-gradient(
to right,
rgba(255, 255, 255, 0),
white 50%,
white
);
background: -o-linear-gradient(
to right,
rgba(255, 255, 255, 0),
white 50%,
white
);
background: -ms-linear-gradient(
to right,
rgba(255, 255, 255, 0),
white 50%,
white
);
background: linear-gradient(
to right,
rgba(255, 255, 255, 0),
white 50%,
white
);
}
效果示例
原文链接:https://blog.csdn.net/weixin_41978102/article/details/105158024
世界有超过 1000 万 Javascript 开发人员,而且这个数字每天都在增加。尽管 JavaScript 以其动态特性而闻名,但它还具有许多其他出色的特性。在这篇博客中,我们将看到 10 个有用的 JavaScript 单行代码,你应该知道它们来提高你的工作效率。
在很多情况下,我们需要在一个范围内生成一个随机数。Math.random() 函数可以为我们生成一个随机数,然后我们可以将其转换为我们想要的范围。
const max = 20;
const min = 10;
// Math.floor() 返回小于或等于一个给定数字的最大整数。
// Math.random() 返回一个浮点型伪随机数字,在0(包括0)和1(不包括)之间。
const random = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(random);
//output: 17
//output: 10
有几种不同的方法可以反转字符串。这是最简单的一个,使用 split() 、reverse() 和 join() 方法。
•split() 方法使用指定的分隔符字符串将一个String对象分割成子字符串数组。 •reverse() 方法将数组中元素的位置颠倒,并返回该数组•join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。
reverse = (str) => str.split('').reverse().join('');
const str = 'hello world';
console.log(reverse(str));
// output: dlrow olleh
适用于元素随机颜色生成的场景
•padEnd() 方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。
'#' +
Math.floor(Math.random() * 0xffffff)
.toString(16)
.padEnd(6, '0');
console.log(color);
//output: #ed19ed
在使用随机算法时,数组的随机排序是一项经常用到的场景,在 JavaScript 中,我们没有模块像python 中的 random.shuffle() 方法一样实现数组元素的随机排序,但仍然有一种方法只需一行代码就可以将数组的所有元素随机排序。
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
const arr = Array.from({ length: 10 }, (_, i) => i + 1);
console.log('array: ', arr);
console.log('shuffled array: ', shuffleArray(arr));
//output:
// array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// shuffled array: [5, 7, 8, 9, 1, 2, 3, 4, 10, 6]
初学者经常会发现自己很难正确地将元素滚动到视图中。滚动元素最简单的方法是使用 scrollIntoView() 方法。
//Add behavior: "smooth" for a smooth scrolling animation.
const scrollToTop = (element) =>
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
const scrollToBottom = (element) =>
element.scrollIntoView({ behavior: 'smooth', block: 'end' });
如果您希望您显示的内容遵循使用您网站的人的配色方案,JavaScript 包含一种检测某人是否使用暗色主题的方法,以便您可以相应地调整颜色。
const isDarkMode1 =
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;
// 如果您想将其用作函数
const isDarkMode2 = () =>
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;
console.log(isDarkMode1);
console.log(isDarkMode2());
//output:
// true
// true
将文本复制到剪贴板非常有用,也是一个难以解决的问题。您可以在网上找到各种解决方案,但下面的解决方案可能是最简洁和最聪明的解决方案之一。
const copyToClipboard = (text) =>
navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
确定如用户的年龄时,你必须计算从某个时间点到现在已经过去的天数。
const ageDays = (old, recent) =>
Math.ceil(Math.abs(old - recent) / (1000 * 60 * 60 * 24)) + ' Day(s)';
const firstDate = new Date('2021-06-10');
const secondDate = new Date('2022-03-03');
console.log(ageDays(firstDate, secondDate));
// output: 266 Day(s)
Javascript 中的 Math.random 函数可用于生成范围之间的随机数。要生成随机布尔值,我们需要随机获取 0 到 1 之间的数字,然后检查它是大于还是小于 0.5。
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
// output: false
我们可以使用 navigator.platform 来检查浏览器运行的平台。
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(navigator.platform);
console.log(isAppleDevice);
// output:
// Win32
// false
注意:此属性的推荐替代方案是 navigator.userAgentData.platform。但是,navigator.userAgentData.platform 还没有被一些主流浏览器支持,并且定义它的规范还没有被任何标准组采用(具体来说,它不是 W3C 或 WHATWG 发布的任何规范的一部分)。
*请认真填写需求信息,我们会在24小时内与您取得联系。