由 CyanHall.com
创建于 2020-11-07,
上次更新:2021-04-30。
👉 如果有用请点赞。
👉 如果有用请点赞。
1. 解构赋值
let [first, last] = ['Cyan', 'Hall']
// or
let {first, last} = {
first: 'Cyan',
last: 'Hall'
}
3. 箭头函数
const getName = user => user.name
const funcName = name => {
// do something
return name
}
5. 数组操作
// Delete at index
array.splice(index, 1)
// Insert at index
array.splice(index, 0, newItem)
// check exist
[1, 2, 3].includes(3) // true
// find index
[1, 2, 3].indexOf(3) // 2; return -1 if not found
// concat
let array3 = array1.concat(array2) // [1].concat([2]) is [1, 2]
// new array
let array4 = [1, 2, 3, 4, 5].slice(2, 4) // [3, 4]
7. 对象展开
const options = {
...defaults,
show: true
}
9. 历遍
for (const i of [1, 2, 3]) {
console.log(i)
}
// 1
// 2
// 3
for (const [index, value] of ['Cyan', 'Hall', '.com'].entries()) {
console.log(index, value)
}
// 0 "Cyan"
// 1 "Hall"
// 2 ".com"
const obj = {part1: 'Cyan', part2: 'Hall', part3: '.com'};
for (const key in obj) {
console.log(key, obj[key])
}
// or
for (const [key, value] of Object.entries(obj)) {
console.log(key, value)
}
// part1 Cyan
// part2 Hall
// part3 .com
11. 收集所有 Promise 返回
let promises = []
// func1 and func2 returns a promise
promises.push(func1())
promises.push(func2())
Promise.all(promises).then(allResult => {
let [result1, resul2] = allResult
// ...
})
13. 生成器
function * countdown(n) {
for (let i = n; i > 0; --i) {
yield i
}
}
[...countdown(3)] // [ 3, 2, 1 ]
let gen = countdown(3)
gen.next() // 3
gen.next() // 2
15. window
const formData = new window.FormData()
formData.append('file', data)
window.localStorage.getItem(key)
window.localStorage.setItem(key, data)
window.location.origin // "https://www.cyanhall.com"
window.location.hostname // "www.cyanhall.com"
window.location.href // "https://www.cyanhall.com/posts/notes/8.javascript-cheatsheet/"
window.open("https://www.cyanhall.com")
window.addEventListener('resize', resizeHandler)
window.removeEventListener('resize', resizeHandler)
17. Email Validation
// From https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript
function validateEmail(email) {
if (email === '') {
return true
}
const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
2. 字符串操作
"CyanHall".includes("yan") // true
"CyanHall".startsWith("Cyan") // true
"CyanHall".endsWith("Hall") // true
'C:yan:Hall'.split(':') // ["C", "yan", "Hall"]
parseFloat("123").toFixed(2) // "123.00"
4. 数组历遍
const numbers = [1, 2, 3]
numbers.map(n => n * 2) // [2, 4, 6]
numbers.filter(n => n % 2 === 0) // [2]
numbers.reduce((prev, next) => prev + next, 0) // 6
numbers.find(n => n > 2) // 3
6. 展开操作符
const array1 = [1, 2]
const array2 = [...array1, 3, 4] // [1, 2, 3, 4]
const funcName = (x, ...params) => {
console.log(x)
console.log(params)
}
funcName(1, 2, 3, 4)
// 1
// [2, 3, 4]
8. 数组展开
const array3 = [
...array1,
...array2,
'newItem'
]
10. 创建 Promise
const funcName = params => {
return new Promise((resolve, reject) => {
// ....
// do something
// if success
resolve(result)
// if fail
reject(error)
})
}
funcName('test')
.then(result => {
// ...
})
.catch(error => {
// ...
})
.finally(() => {
// ...
})
12. Async-await
const funcName = async () => {
const data = await fetchData()
return data
}
await funcName()
14. 浏览器
encodeURIComponent() // Encodes a URI into UTF-8
decodeURIComponent() // Decodes
16. XMLHttpRequest
// Download excel file
const xhr = new window.XMLHttpRequest()
const applicationType = 'application/vnd.ms-excel; charset=UTF-8'
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8')
xhr.onload = function(e) {
if (this.status === 200) {
let blob = new window.Blob([this.response], { type: applicationType })
let downloadUrl = window.URL.createObjectURL(blob)
let a = document.createElement('a')
a.href = downloadUrl
a.download = fileName
a.click()
}
}
xhr.onreadystatechange = e => {
if (xhr.readyState === 4) {
//
} else if (xhr.readyState === 3) {
//
})
}
xhr.send()
更多