、生成隨機字符串
我們可以使用 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、暫停一會
碼必須盡可能的清晰和易讀。
這實際上是一種編程藝術 —— 以一種正確并且人們易讀的方式編碼來完成一個復雜的任務。一個良好的代碼風格大大有助于實現這一點。
下面是一個備忘單,其中列出了一些建議的規則(詳情請參閱下文):
現在,讓我們詳細討論一下這些規則和它們的原因吧。
沒有什么規則是“必須”的
沒有什么規則是“刻在石頭上”的。這些是風格偏好,而不是宗教教條。
在大多數的 JavaScript 項目中,花括號以 “Egyptian” 風格(譯注:“egyptian” 風格又稱 K&R 風格 — 代碼段的開括號位于一行的末尾,而不是另起一行的風格)書寫,左花括號與相應的關鍵詞在同一行上 — 而不是新起一行。左括號前還應該有一個空格,如下所示:
if (condition) {
// do this
// ...and that
// ...and that
}
單行構造(如 if (condition) doSomething())也是一個重要的用例。我們是否應該使用花括號?如果是,那么在哪里?
下面是這幾種情況的注釋,你可以自己判斷一下它們的可讀性:
對于很短的代碼,寫成一行是可以接受的:例如 if (cond) return null。但是代碼塊(最后一個示例)通常更具可讀性。
沒有人喜歡讀一長串代碼,最好將代碼分割一下。
例如:
// 回勾引號 ` 允許將字符串拆分為多行
let str=`
ECMA International's TC39 is a group of JavaScript developers,
implementers, academics, and more, collaborating with the community
to maintain and evolve the definition of JavaScript.
`;
對于 if 語句:
if (
id===123 &&
moonPhase==='Waning Gibbous' &&
zodiacSign==='Libra'
) {
letTheSorceryBegin();
}
一行代碼的最大長度應該在團隊層面上達成一致。通常是 80 或 120 個字符。
有兩種類型的縮進:
show(parameters,
aligned, // 5 spaces padding at the left
one,
after,
another
) {
// ...
}
function pow(x, n) {
let result=1;
// <--
for (let i=0; i < n; i++) {
result *=x;
}
// <--
return result;
}
插入一個額外的空行有助于使代碼更具可讀性。寫代碼時,不應該出現連續超過 9 行都沒有被垂直分割的代碼。
每一個語句后面都應該有一個分號。即使它可以被跳過。
有一些編程語言的分號確實是可選的,那些語言中也很少使用分號。但是在 JavaScript 中,極少數情況下,換行符有時不會被解釋為分號,這時代碼就容易出錯。更多內容請參閱 代碼結構 一章的內容。
如果你是一個有經驗的 JavaScript 程序員,你可以選擇像 StandardJS 這樣的無分號的代碼風格。否則,最好使用分號以避免可能出現的陷阱。大多數開發人員都應該使用分號。
盡量避免代碼嵌套層級過深。
例如,在循環中,有時候使用 continue 指令以避免額外的嵌套是一個好主意。
例如,不應該像下面這樣添加嵌套的 if 條件:
for (let i=0; i < 10; i++) {
if (cond) {
... // <- 又一層嵌套
}
}
我們可以這樣寫:
for (let i=0; i < 10; i++) {
if (!cond) continue;
... // <- 沒有額外的嵌套
} //多用這種風格。
使用 if/else 和 return 也可以做類似的事情。
例如,下面的兩個結構是相同的。
第一個:
function pow(x, n) {
if (n < 0) {
alert("Negative 'n' not supported");
} else {
let result=1;
for (let i=0; i < n; i++) {
result *=x;
}
return result;
}
}
第二個:
function pow(x, n) {
if (n < 0) {
alert("Negative 'n' not supported");
return;
}
let result=1;
for (let i=0; i < n; i++) {
result *=x;
}
return result;
}
但是第二個更具可讀性,因為 n < 0 這個“特殊情況”在一開始就被處理了。一旦條件通過檢查,代碼執行就可以進入到“主”代碼流,而不需要額外的嵌套。
如果你正在寫幾個“輔助”函數和一些使用它們的代碼,那么有三種方式來組織這些函數。
// function declarations
function createElement() {
...
}
function setHandler(elem) {
...
}
function walkAround() {
...
}
// the code which uses them
let elem=createElement();
setHandler(elem);
walkAround();
// the code which uses the functions
let elem=createElement();
setHandler(elem);
walkAround();
// --- helper functions ---
function createElement() {
...
}
function setHandler(elem) {
...
}
function walkAround() {
...
}
大多數情況下,第二種方式更好。
這是因為閱讀代碼時,我們首先想要知道的是“它做了什么”。如果代碼先行,那么在整個程序的最開始就展示出了這些信息。之后,可能我們就不需要閱讀這些函數了,尤其是它們的名字清晰地展示出了它們的功能的時候。
風格指南包含了“如果編寫”代碼的通用規則,例如:使用哪個引號、用多少空格來縮進、一行代碼最大長度等非常多的細節。
當團隊中的所有成員都使用相同的風格指南時,代碼看起來將是統一的。無論是團隊中誰寫的,都是一樣的風格。
當然,一個團隊可以制定他們自己的風格指南,但是沒必要這樣做?,F在已經有了很多制定好的代碼風格指南可供選擇。
一些受歡迎的選擇:
如果你是一個初學者,你可以從本章中上面的內容開始。然后你可以瀏覽其他風格指南,并選擇一個你最喜歡的。
檢查器(Linters)是可以自動檢查代碼樣式,并提出改進建議的工具。
它們的妙處在于進行代碼風格檢查時,還可以發現一些代碼錯誤,例如變量或函數名中的錯別字。因此,即使你不想堅持某一種特定的代碼風格,我也建議你安裝一個檢查器。
下面是一些最出名的代碼檢查工具:
它們都能夠做好代碼檢查。我使用的是 ESLint。
大多數檢查器都可以與編輯器集成在一起:只需在編輯器中啟用插件并配置代碼風格即可。
例如,要使用 ESLint 你應該這樣做:
下面是一個 .eslintrc 文件的例子:
{
"extends": "eslint:recommended",
"env": {
"browser": true,
"node": true,
"es6": true
},
"rules": {
"no-console": 0,
"indent": 2
}
}
這里的 "extends" 指令表示我們是基于 “eslint:recommended” 的設置項而進行設置的。之后,我們制定我們自己的規則。
你也可以從網上下載風格規則集并進行擴展。有關安裝的更多詳細信息
此外,某些 IDE 有內置的檢查器,這非常方便,但是不像 ESLint 那樣可自定義。
本文描述的(和提到的代碼風格指南中的)所有語法規則,都旨在幫助你提高代碼可讀性。它們都是值得商榷的。
當我們思考如何寫“更好”的代碼的時候,我們應該問自己的問題是:“什么可以讓代碼可讀性更高,更容易被理解?”和“什么可以幫助我們避免錯誤?”這些是我們討論和選擇代碼風格時要牢記的主要原則。
閱讀流行的代碼風格指南,可以幫助你了解有關代碼風格的變化趨勢和最佳實踐的最新想法。
、垂直對齊
如果你用CSS,則你會有困惑:我該怎么垂直對齊容器中的元素?現在,利用CSS3的Transform,可以很優雅的解決這個困惑:
.verticalcenter{ position: relative; top: 50%; -webkit-transform: translateY(-50%); -o-transform: translateY(-50%); transform: translateY(-50%); }
2、伸展一個元素到窗口高度
在具體場景中,你可能想要將一個元素伸展到窗口高度,基本元素的調整只能調整容器的大小,因此要使一個元素伸展到窗口高度,我們需要伸展頂層元素:html
和body
:
html, body { height: 100%; }
然后將100%應用到任何元素的高:
div { height: 100%;}
3、基于文件格式使用不同的樣式
為了更容易知道鏈接的目標,有時你想讓一些鏈接看起來和其它的不同。下面的片段在文本鏈接前添加一個圖標,對不同的資源使用不同的圖標或圖片:
a[href^="http://"]{ padding-right: 20px; background: url(external.gif) no-repeat center right; } /* emails */ a[href^="mailto:"]{ padding-right: 20px; background: url(email.png) no-repeat center right; } /* pdfs */ a[href$=".pdf"]{ padding-right: 20px; background: url(pdf.png) no-repeat center right; }
4、創建跨瀏覽器的圖像灰度
灰度有時看起來簡約和優雅,能為網站呈現更深層次的色調。在示例中,我們將對一個SVG圖像添加灰度過濾:
<svg xmlns="http://www.w3.org/2000/svg"> <filter id="grayscale"> <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"/> </filter></svg>
為了跨瀏覽器,會用到filter
屬性:
img { filter: url(filters.svg#grayscale); /* Firefox 3.5+ */ filter: gray; /* IE6-9 */ -webkit-filter: grayscale(1); /* Google Chrome, Safari 6+ & Opera 15+ */}
5、背景漸變動畫
CSS中最具誘惑的一個功能是能添加動畫效果,除了漸變,你可以給背景色、透明度、元素大小添加動畫。目前,你不能為漸變添加動畫,但下面的代碼可能有幫助。它通過改變背景位置,讓它看起來有動畫效果。
button { background-image: linear-gradient(#5187c4, #1c2f45); background-size: auto 200%; background-position: 0 100%; transition: background-position 0.5s; } button:hover { background-position: 0 0; }
6、CSS:表格列寬自適用
對于表格,當談到調整列寬時,是比較痛苦的。然后,這里有一個可以使用的技巧:給td
元素添加 white-space: nowrap;
能讓文本正確的換行
td { white-space: nowrap;}
213126486編號:悟空
7、只在一邊或兩邊顯示盒子陰影
如果你要一個盒陰影,試試這個技巧,能為任一邊添加陰影。為了實現這個,首先定義一個有具體寬高的盒子,然后正確定位:after
偽類。實現底邊陰影的代碼如下:
.box-shadow { background-color: #FF8020; width: 160px; height: 90px; margin-top: -45px; margin-left: -80px; position: absolute; top: 50%; left: 50%; } .box-shadow:after { content: ""; width: 150px; height: 1px; margin-top: 88px; margin-left: -75px; display: block; position: absolute; left: 50%; z-index: -1; -webkit-box-shadow: 0px 0px 8px 2px #000000; -moz-box-shadow: 0px 0px 8px 2px #000000; box-shadow: 0px 0px 8px 2px #000000; }
8、包裹長文本
如果你碰到一個比自身容器長的文本,這個技巧對你很有用。在這個示例中,默認時,不管容器的寬度,文本都將水平填充。
簡單的CSS代碼就能在容器中調整文本:
pre { white-space: pre-line; word-wrap: break-word;}
9、制造模糊文本
想要讓文本模糊?可以使用color
透明和text-shadow
實現。
.blurry-text { color: transparent; text-shadow: 0 0 5px rgba(0,0,0,0.5);}
10、用CSS動畫實現省略號動畫
這個片段將幫助你制造一個ellipsis的動畫,對于簡單的加載狀態是很有用的,而不用去使用gif圖像。
.loading:after { overflow: hidden; display: inline-block; vertical-align: bottom; animation: ellipsis 2s infinite; content: "\2026"; /* ascii code for the ellipsis character */ } @keyframes ellipsis { from { width: 2px; } to { width: 15px; } }
11、樣式重置
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; outline: none; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } html { height: 101%; } body { font-size: 62.5%; line-height: 1; font-family: Arial, Tahoma, sans-serif; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } strong { font-weight: bold; } table { border-collapse: collapse; border-spacing: 0; } img { border: 0; max-width: 100%; } p { font-size: 1.2em; line-height: 1.0em; color: #333; }
12、典型的CSS清除浮動
.clearfix:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } .clearfix { display: inline-block; } html[xmlns] .clearfix { display: block; } * html .clearfix { height: 1%; }
13、新版清除浮動(2011)
.clearfix:before, .container:after { content: ""; display: table; } .clearfix:after { clear: both; } /* IE 6/7 */ .clearfix { zoom: 1; }
14、跨瀏覽器的透明
.transparent { filter: alpha(opacity=50); /* internet explorer */ -khtml-opacity: 0.5; /* khtml, old safari */ -moz-opacity: 0.5; /* mozilla, netscape */ opacity: 0.5; /* fx, safari, opera */}
15、CSS引用模板
blockquote { background: #f9f9f9; border-left: 10px solid #ccc; margin: 1.5em 10px; padding: .5em 10px; quotes: "\201C""\201D""\2018""\2019"; } blockquote:before { color: #ccc; content: open-quote; font-size: 4em; line-height: .1em; margin-right: .25em; vertical-align: -.4em; } blockquote p { display: inline; }
16、個性圓角
#container { -webkit-border-radius: 4px 3px 6px 10px; -moz-border-radius: 4px 3px 6px 10px; -o-border-radius: 4px 3px 6px 10px; border-radius: 4px 3px 6px 10px; } /* alternative syntax broken into each line */ #container { -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 3px; -webkit-border-bottom-right-radius: 6px; -webkit-border-bottom-left-radius: 10px; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 3px; -moz-border-radius-bottomright: 6px; -moz-border-radius-bottomleft: 10px; }
17、自定義文本選擇
::selection { background: #e2eae2; } ::-moz-selection { background: #e2eae2; } ::-webkit-selection { background: #e2eae2; }
18、為logo隱藏H1
h1 { text-indent: -9999px; margin: 0 auto; width: 320px; height: 85px; background: transparent url("images/logo.png") no-repeat scroll; }
19、圖片邊框偏光
img.polaroid { background:#000; /*Change this to a background image or remove*/ border:solid #fff; border-width:6px 6px 20px 6px; box-shadow:1px 1px 5px #333; /* Standard blur at 5px. Increase for more depth */ -webkit-box-shadow:1px 1px 5px #333; -moz-box-shadow:1px 1px 5px #333; height:200px; /*Set to height of your image or desired div*/ width:200px; /*Set to width of your image or desired div*/ }
20、錨鏈接偽類
*請認真填寫需求信息,我們會在24小時內與您取得聯系。