看完这篇文章,你将了解
- == 和 === 的区别
- onload, onpageshow 和 DOMContentLoaded 的区别
== 和 === 的区别
根据 stackoverflow 上的相关讨论
它们的主要区别是:
- == 只比较值,不比较类型, (如果两边类型不一样,会自动转换成同一类型)
- === 既比较值,又比较类型
以下是《JavaScript: The Good Parts》的原话:
JavaScript has two sets of equality operators:
===
and!==
, and their evil twins==
and!=
. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then===
producestrue
and!==
producesfalse
. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:'' == '0' // false 0 == '' // true 0 == '0' // true false == 'false' // false false == '0' // true false == undefined // false false == null // false null == undefined // true ' \t\r\n ' == 0 // true
The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use
===
and!==
. All of the comparisons just shown producefalse
with the===
operator.
== 与 === 一个相同点就是在比较引用类型时表现一致
我想,因为引用存的是地址。既然大家类型都一样,都是地址,那么在此前提下对比的只是地址值
onload, onpageShow, DOMContentLoaded 的区别
首先,它们通过
window.onload = fn
window.onpageshow = fn)
document.addEventListener('DOMContentLoaded', fn) // 跟前面不一样,注意这是一个 DOM 方法
调用。
其次,区别是:
- DOMContentLoaded 是加载完 html 文档后触发,不管 link 里的样式文件,img 里的图片文件等是否就绪
- onload 是在 DOMContentLoaded 基础上,加载完所有资源之后触发
- onpageshow 与 onload 触发条件一样,只不过 onload 在浏览器从页面缓存中取页面时不触发,而 onpageshow 总会触发
发生顺序如下:
- DOMContentLoaded
- onload
- onpageshow
demo
window.onload = function() {
alert('onload')
}
window.onpageshow = function() {
alert('pageshow')
}
document.addEventListener('DOMContentLoaded', function() {
alert('DOMContentLoaded')
})
改善 JS 执行效率的两个 tip
这几天在力扣上刷题,发现一个规律。
一些 JS,在解题思路一样的情况下,改变 for 的遍历逻辑,先后顺序也能在一定程度上缩短执行时间
- 比如一道字符串题,我从斜对角线(撇的顺序)遍历改为行序遍历速度改善明显
- 比如一道动态规划,我将原先 for 循环里四个状态判断抽出两个在外面预执行,时间减半
除此之外,数组的 push 方法,执行速度不如 String 加法
- 比如一道字符串题,我原本用字符数组处理
str.push(string)
,后来改为str += string
,效率大增
暂无评论