、生成隨機(jī)字符串
我們可以使用 Math.random 生成一個(gè)隨機(jī)字符串,當(dāng)我們需要一個(gè)唯一的 ID 時(shí)非常方便。
const randomString = () => Math.random().toString(36).slice(2)
randomString() // gi1qtdego0b
randomString() // f3qixv40mot
randomString() // eeelv1pm3ja
2、轉(zhuǎn)義HTML特殊字符
如果您了解 XSS,其中一種解決方案是轉(zhuǎn)義 HTML 字符串。
const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]))
escape('<div class="medium">Hi Medium.</div>')
// <div class="medium">Hi Medium.</div>
3、將字符串中每個(gè)單詞的第一個(gè)字符大寫(xiě)
此方法用于將字符串中每個(gè)單詞的第一個(gè)字符大寫(xiě)。
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
uppercaseWords('hello world'); // 'Hello World'
另外,在這里,我要謝謝克里斯托弗·斯特羅利亞-戴維斯,他還跟我分享了他的更加簡(jiǎn)單的方法,代碼如下:
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
4、將字符串轉(zhuǎn)換為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、刪除數(shù)組中的重復(fù)值
刪除數(shù)組的重復(fù)項(xiàng)是非常有必要的,使用“Set”會(huì)變得非常簡(jiǎn)單。
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、 展平一個(gè)數(shù)組
我們經(jīng)常在面試中受到考驗(yàn),這可以通過(guò)兩種方式來(lái)實(shí)現(xiàn)。
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、從數(shù)組中刪除虛假值
使用此方法,您將能夠過(guò)濾掉數(shù)組中的所有虛假值。
const removeFalsy = (arr) => arr.filter(Boolean)
removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])
// ['a string', true, 5, 'another string']
8、檢查一個(gè)數(shù)字是偶數(shù)還是奇數(shù)
超級(jí)簡(jiǎn)單的任務(wù),可以通過(guò)使用模運(yùn)算符 (%) 來(lái)解決。
const isEven = num => num % 2 === 0
isEven(2) // true
isEven(1) // false
9、獲取兩個(gè)數(shù)字之間的隨機(jī)整數(shù)
此方法用于獲取兩個(gè)數(shù)字之間的隨機(jī)整數(shù)。
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 50) // 25
random(1, 50) // 34
10、獲取參數(shù)的平均值
我們可以使用 reduce 方法來(lái)獲取我們?cè)诖撕瘮?shù)中提供的參數(shù)的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5); // 3
11、將數(shù)字截?cái)酁楣潭ㄐ?shù)點(diǎn)
使用 Math.pow() 方法,可以將一個(gè)數(shù)字截?cái)酁槲覀冊(cè)诤瘮?shù)中提供的某個(gè)小數(shù)點(diǎn)。
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、計(jì)算兩個(gè)日期相差天數(shù)
有時(shí)候我們需要計(jì)算兩個(gè)日期之間的天數(shù),一行代碼就可以搞定。
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、從日期中獲取一年中的哪一天
如果我們想知道某個(gè)日期是一年中的哪一天,我們只需要一行代碼即可實(shí)現(xiàn)。
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
dayOfYear(new Date()) // 74
14、生成一個(gè)隨機(jī)的十六進(jìn)制顏色
如果你需要一個(gè)隨機(jī)的顏色值,這個(gè)函數(shù)就可以了。
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`
randomColor() // #9dae4f
randomColor() // #6ef10e
15、將RGB顏色轉(zhuǎn)換為十六進(jìn)制
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、檢測(cè)暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
18、交換兩個(gè)變量
[foo, bar] = [bar, foo]
19、暫停一會(huì)
我們的日常開(kāi)發(fā)工作中,文本溢出截?cái)嗍÷允呛艹R?jiàn)的一種需考慮的業(yè)務(wù)場(chǎng)景細(xì)節(jié)。看上去 “稀松平常” ,但在實(shí)現(xiàn)上卻有不同的區(qū)分,是單行截?cái)噙€是多行截?cái)啵慷嘈械慕財(cái)嗯袛嗍腔谛袛?shù)還是基于高度?這些問(wèn)題之下,都有哪些實(shí)現(xiàn)方案?他們之間的差異性和場(chǎng)景適應(yīng)性又是如何?
一般來(lái)說(shuō),在做這樣文字截?cái)嘈Ч麜r(shí)我們更多是希望:
基于上述的準(zhǔn)則,下面我們通過(guò)編碼實(shí)踐,給出一些答案。
核心 CSS 語(yǔ)句
優(yōu)點(diǎn)
短板
適用場(chǎng)景
Demo
<div class="demo">
床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光
</div>
.demo {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
效果示例
核心 CSS 語(yǔ)句
優(yōu)點(diǎn)
短板
適用場(chǎng)景
Demo
<div class="demo">
床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光
</div>
.demo {
display: -webkit-box;
overflow: hidden;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
效果示例
核心 CSS 語(yǔ)句
優(yōu)點(diǎn)
短板
適用場(chǎng)景
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 語(yǔ)句
優(yōu)點(diǎn)
短板
適用場(chǎng)景
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
世界有超過(guò) 1000 萬(wàn) Javascript 開(kāi)發(fā)人員,而且這個(gè)數(shù)字每天都在增加。盡管 JavaScript 以其動(dòng)態(tài)特性而聞名,但它還具有許多其他出色的特性。在這篇博客中,我們將看到 10 個(gè)有用的 JavaScript 單行代碼,你應(yīng)該知道它們來(lái)提高你的工作效率。
在很多情況下,我們需要在一個(gè)范圍內(nèi)生成一個(gè)隨機(jī)數(shù)。Math.random() 函數(shù)可以為我們生成一個(gè)隨機(jī)數(shù),然后我們可以將其轉(zhuǎn)換為我們想要的范圍。
const max = 20;
const min = 10;
// Math.floor() 返回小于或等于一個(gè)給定數(shù)字的最大整數(shù)。
// Math.random() 返回一個(gè)浮點(diǎn)型偽隨機(jī)數(shù)字,在0(包括0)和1(不包括)之間。
const random = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(random);
//output: 17
//output: 10
有幾種不同的方法可以反轉(zhuǎn)字符串。這是最簡(jiǎn)單的一個(gè),使用 split() 、reverse() 和 join() 方法。
?split() 方法使用指定的分隔符字符串將一個(gè)String對(duì)象分割成子字符串?dāng)?shù)組。 ?reverse() 方法將數(shù)組中元素的位置顛倒,并返回該數(shù)組?join() 方法將一個(gè)數(shù)組(或一個(gè)類(lèi)數(shù)組對(duì)象)的所有元素連接成一個(gè)字符串并返回這個(gè)字符串。如果數(shù)組只有一個(gè)項(xiàng)目,那么將返回該項(xiàng)目而不使用分隔符。
reverse = (str) => str.split('').reverse().join('');
const str = 'hello world';
console.log(reverse(str));
// output: dlrow olleh
適用于元素隨機(jī)顏色生成的場(chǎng)景
?padEnd() 方法會(huì)用一個(gè)字符串填充當(dāng)前字符串(如果需要的話(huà)則重復(fù)填充),返回填充后達(dá)到指定長(zhǎng)度的字符串。從當(dāng)前字符串的末尾(右側(cè))開(kāi)始填充。
'#' +
Math.floor(Math.random() * 0xffffff)
.toString(16)
.padEnd(6, '0');
console.log(color);
//output: #ed19ed
在使用隨機(jī)算法時(shí),數(shù)組的隨機(jī)排序是一項(xiàng)經(jīng)常用到的場(chǎng)景,在 JavaScript 中,我們沒(méi)有模塊像python 中的 random.shuffle() 方法一樣實(shí)現(xiàn)數(shù)組元素的隨機(jī)排序,但仍然有一種方法只需一行代碼就可以將數(shù)組的所有元素隨機(jī)排序。
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]
初學(xué)者經(jīng)常會(huì)發(fā)現(xiàn)自己很難正確地將元素滾動(dòng)到視圖中。滾動(dòng)元素最簡(jiǎn)單的方法是使用 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' });
如果您希望您顯示的內(nèi)容遵循使用您網(wǎng)站的人的配色方案,JavaScript 包含一種檢測(cè)某人是否使用暗色主題的方法,以便您可以相應(yīng)地調(diào)整顏色。
const isDarkMode1 =
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;
// 如果您想將其用作函數(shù)
const isDarkMode2 = () =>
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;
console.log(isDarkMode1);
console.log(isDarkMode2());
//output:
// true
// true
將文本復(fù)制到剪貼板非常有用,也是一個(gè)難以解決的問(wèn)題。您可以在網(wǎng)上找到各種解決方案,但下面的解決方案可能是最簡(jiǎn)潔和最聰明的解決方案之一。
const copyToClipboard = (text) =>
navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
確定如用戶(hù)的年齡時(shí),你必須計(jì)算從某個(gè)時(shí)間點(diǎn)到現(xiàn)在已經(jīng)過(guò)去的天數(shù)。
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 函數(shù)可用于生成范圍之間的隨機(jī)數(shù)。要生成隨機(jī)布爾值,我們需要隨機(jī)獲取 0 到 1 之間的數(shù)字,然后檢查它是大于還是小于 0.5。
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
// output: false
我們可以使用 navigator.platform 來(lái)檢查瀏覽器運(yùn)行的平臺(tái)。
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 還沒(méi)有被一些主流瀏覽器支持,并且定義它的規(guī)范還沒(méi)有被任何標(biāo)準(zhǔn)組采用(具體來(lái)說(shuō),它不是 W3C 或 WHATWG 發(fā)布的任何規(guī)范的一部分)。
*請(qǐng)認(rèn)真填寫(xiě)需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。