new Image()
等价于 document.createElement(‘img’)
let img = new Image(50, 50)img.src = '...'document.body.appendChild(img)
for…in 与 for…of
for...in以任意顺序遍历一个对象的除Symbol以外的可枚举属性,不建议与数组一起使用let obj = {a: 1,b: true,c: 'hello'}for (let key in obj) {console.log(obj[key]) // 1, true, 'hello'}
for...of在可迭代的对象(Array、Map、Set、String、TypedArray、arguments、…)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句let arr = [1, 2, 3]for (let n of arr) {console.log(n) // 1, 2, 3}
获取元素绑定的监听事件
getEventListner(el) // el 元素
ASCII
小写字母 a-z:97-122大写字母 A-Z:65-90数字 0-9:48-57
Percent-encoding
百分比编码 (有时也被称为URL编码)是一种拥有8位字符编码的编码机制,这些编码在URL的上下文中具有特定的含义;
编码由英文字母替换组成:“%”后跟替换字符的ASCII的十六进制表示。
需要编码的字符对象遍历
for...in与Object.keys()无法保证对象遍历的顺序,且不同浏览器产生的结果可能不一样,应该避免在对属性顺序有要求的场景中使用。对象拷贝
Array.map
生成32位随机码
function createRandomCode () {let timestamp = new Date().getTime().toString();let arr = 'abcdefghijklmnopqrstuvwsyz0123456789'.split('');let nonce = '',len = 32 - timestamp.length;for (let i = 0; i < timestamp.length; i++) {nonce += arr[timestamp[i]];}for (let j = 0; j < len; j++) {let num = Math.round(Math.random() * 35);nonce += arr[num];}return nonce;}
生成带参数的url
function createUrl (baseUrl, params) {let url = baseUrl + '?';for(let key in params) {url += key + '=' + params[key] + '&';}return url.substring(0, url.lastIndexOf('&'));}
迭代NodeList
NodeList 不是一个数组,是一个类似数组的对象(类数组)
- 直接使用
forEach() - 先使用
Array.from()将其转换为数组,然后再迭代 - 若上述两个方法浏览器都不支持,则可以使用
Array.prototype.forEach()字符串的 substr 和 substring
数组的 slice 与 splice
获取url链接中的参数
function getUrlQuery (name) {let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i")let r = window.location.search.substring(1).match(reg)return r ? r[2] : null}
区分window.prompt的确定与取消
let value = window.prompt('这是一个带有输入的提示')if (value || value === '') {// 确定} else {// 取消}
typeof
typeof '' // "string"typeof 0 // "number"typeof true // "boolean"typeof [] // "object"typeof {} // "object"typeof null // "object"typeof undefined // "undefined"typeof function() {} // "function"typeof Object // "function"typeof Symbol() // "symbol" (EAMAScript 2015)typeof 1n // "bigint" (EAMAScript 2020)
判断一个对象是否数组
```javascript typeof [] // “object” ❌
Object.prototype.toString.call([]) // “[object Array]” ✅
Array.isArray([]) // true 👍
<a name="jqiRm"></a>## 对象数组去重> new Map()```javascript// citys [{ id: 1, city: '北京'}, { id: 2, city: '上海'}, { id: 1, city: '北京'}, { id: 3, city: '广州'}, { id: 4, city: '深圳'}]function deDuplicate() {let idMap = new Map()citys.map(item => {if (idMap.has(item.id)) returnidMap.set(item.id, item)})return [...idMap.values()]}
判断空对象
JSON.stringify({}=== '{}'Object.keys({}).length === 0
encodeURI 与 encodeURIComponent
encodeURI 一般用于完整的URI,encodeURIComponent 一般用于 URI 组件
: , ; @ / ? & = + $ // 保留字符- _ . ! ~ * ' ( ) // 不转义字符 🎯A-Z a-z 0-9 // 字母、数字 🎯# // 数字标志
对于以上字符,encodeURI 都不会进行编码;encodeURIComponent 除不转义字符、字母、数字外,其余的都会被编码;对于空格,两种方法编码一个空格时都会转换成 %20;
