- 时间:2022-10-27 00:32 编辑: 来源: 阅读:306
- 扫一扫,手机访问
摘要:相等的时候应该用Object.is()。
[源码分享]
= =我们都知道JavasSript是弱类型,当我们使用= =进行比较时,在少数情况下,会因为类型转换或者运算符说“将两个操作数中的一个转换为另一个,然后进行比较”而出现意外结果。 //0 = = ' '//true//null = = undefined//true//[1]= = true//true console . log(' 0 = = " " ',0 = = ' ');//true console . log(' null = = undefined ',null = = undefined);// trueconsole.log('[1] == true ',[1]= = true);// true===所以JavaScript中提供同余运算符==比非同余运算符更严格,没有类型转换。 但与= = =相比并不是最佳方案。 您可能会得到://nan = = nan//false console . log(' nan = = nan ',nan = = nan);// falseObject.is()好消息是ES6中提供了一个新的Object.is()方法。它有= = =的几个特点,而且更好更准确。在少数特例中得到很好的体现:// Object.is(0,' ');//false// Object.is(null,未定义);//false// Object.is([1],true);//false// Object.is(NaN,NaN);//trueconsole.log('Object.is(0," "),Object.is(0,' '));//false console . log(' Object.is(null,undefined)',object . is(null,undefined));//false console . log(' Object.is([1],true)',object . is([1],true));//false console . log(' Object.is(NaN,NaN)',object . is(NaN,NaN));// trueMozilla团队并不认为Object.is比= = =更“严格”。他们说我们要考虑的是这个方法如何求解NaN,-0和+0。 但总的来说,我觉得在实际应用中是个不错的做法。