记录下工作中使用JavaScript的心得:
1、Object.freeze可以冻结对象,移除setter和getter属性,只需单向绑定的时候可用
在vue中还可以通过在beforeCreate中给this添加属性实现单向绑定
2、reduce可以按某种规则将数组转换成其他类型
let list = [
{ id: 1, name: 'A', parentId: 0 },
{ id: 2, name: 'B', parentId: 0 },
]
let result = list.reduce((prev, cur) => (prev[cur.id] = cur, prev), {})
3、Array.from生成一定长度的数组
let data = Array.from({length: 10}, (_, idx) => (
new Array()
))
4、使用Map加正则处理复杂逻辑
function handle(val) {
const actions = new Map([
[
/^[1-2]$/,
() => {
console.log(1)
}
],
[
/^[3-4]$/,
() => {
console.log(3)
}
]
])
const action = [...actions].filter(([key, value]) => key.test(`${val}`))
action.map(([key, value]) => {
value.call(this)
})
}
5、解构赋值
const { name, age } = this
布尔类型默认值
function ({ isShow = true } = {}) {}
6、利用Promise.resolve进行异步操作
function asynchronous(params) {
return Promise.resolve()
}
asynchronous().then(() => {
alert(1)
})
7、得到一个打乱顺序的数组
let newArr = JSON.parse(JSON.stringify(oldArr)).sort(
(a, b) => Math.random() - 0.5
)
8、动态获取元素宽高
function textSize(text) {
let span = document.createElement('span')
let result = span.offsetWidth
span.style.visibility = 'hidden'
span.style.fontSize = '18px'
span.style.fontFamily = 'Arial'
span.style.display = 'inline-block'
document.body.appendChild(span)
if (typeof span.textContent != 'undefined') {
span.textContent = text
} else {
span.innerText = text
}
result = parseFloat(window.getComputedStyle(span).width) - result
document.body.removeChild(span)
return result
}
9、循环时,将次数少的放在外层,可以提高性能
for (let i = 0; i < 100; i++) {
for (let j = 0; j < 1000; j++) {
for (let k = 0; k < 10000; k++) {
}
}
}
10、取对象数组某属性最大值
Math.max.apply(
Math,
array.map(item => {
return item.data
})
)
11、实现Promise.finally
finally
方法返回一个Promise。在promise结束时,无论结果是fulfilled或者是rejected,都会执行指定的回调函数。这为在Promise
是否成功完成后都需要执行的代码提供了一种方式。
这避免了同样的语句需要在then和catch中各写一次的情况,本质上是then方法的特例
Promise.prototype.finally = function(cb) {
let con = this.constructor
return this.then(
value => con.resolve(cb()).then(() => value),
reason =>
con.resolve(cb()).then(() => {
throw reason
})
)
}