5個(gè)你可能不知道的神奇JavaScript知識(shí)點(diǎn)!

最近,我遇到了一些奇怪而有趣的面試題,它們與常規(guī)問題不同,這些面試問題看起來很簡單,但它們會(huì)測(cè)試你對(duì) JavaScript 的透徹理解,今天我就來跟大家分享5個(gè)神奇的JavaScript知識(shí)點(diǎn),看看你能答對(duì)幾個(gè)?
現(xiàn)在,我們就馬上開始吧。
1. “x !== x”可以返回true嗎?
輸出“hello fatfish”的“x”值應(yīng)該是多少?
const x = ? // Please fill in the value of "x?if (x !== x) {console.log('hello fatfish')}
太奇妙了,是否存在不等于自身的值?但是,JavaScript 中有一個(gè)值 NaN,它不等于任何值,甚至不等于自身。
const x = NaN // Please fill in the value of "x?if (x !== x) {console.log('hello fatfish')}console.log(NaN === NaN) // falseconsole.log(x !== x) // trueconsole.log(Number.isNaN(x)) // true
2. (!isNaN(x) && x !== x) 可以返回true嗎?
好的,當(dāng)我們過濾掉“NaN”時(shí),還有什么值可以讓一個(gè)值不等于自己呢?
const x = ? // Please fill in the value of "x?if(!isNaN(x) && x !== x) {console.log('hello fatfish')}
也許你知道“object.Defineproperty”,它可以幫助我們解決這個(gè)問題。
window.x = 0 // Any value is OKObject.defineProperty(window, 'x', {get () {return Math.random()}})console.log(x) // 0.12259077808826002console.log(x === x) // falseconsole.log(x !== x) // true
3. 如何使“x === x + 1”?
這個(gè)問題可能并不容易,但只要你了解 JavaScript,你就會(huì)知道“Number.MAX_SAFE_INTEGER 常量代表 JavaScript 中的最大安全整數(shù) (2?3 — 1)。”(這個(gè)解釋來自 MDN)
const x = ? // Please fill in the value of "x?if (x === x + 1) {console.log('hello fatfish')}
所以我們可以為“x”分配任何大于“Number.MAX_SAFE_INTEGER”的值。
const x = Number.MAX_SAFE_INTEGER + 1 // Please fill in the value of "x?if (x === x + 1) {console.log('hello fatfish')}
4. “x > x”可以是true的嗎?
我不想再看了,這是什么垃圾問題?
const x = ? // Please fill in the value of "x?if (x > x) {console.log('hello fatfish')}
雖然,看起來不太可能,但是一個(gè)值怎么可能大于它自己呢?但是,我們可以使用“Symbol.toPrimitive”功能來完成問題。
const x = { // Please fill in the value of "x?value: 1,[] () {console.log('x', this.value)return --this.value}}if (x > x) {console.log('hello fatfish')}
哦,真是太精彩了!
5. typeof x === ‘undefined’ && x.length > 0 ?
const x = ? // Please fill in the value of "x?if(typeof x === 'undefined' && x.length > 0) {console.log('hello fatfish')}
我不得不承認(rèn) JavaScript 是一門了不起的語言。除了 undefined 本身,還有什么值可以讓 typeof x === undefined” 為真呢?
答案是文檔。All 一個(gè) HTMLAllCollection,它包含文檔中的每個(gè)元素(來自 MDN)。
const x = document.all // Please fill in the value of "x?if(typeof x === 'undefined' && x.length > 0) {console.log('hello fatfish')}console.log(x)console.log(typeof x)console.log(x === undefined)
這些問題是不是很神奇?
寫在最后
以上就是我今天跟你分享的5個(gè)非常有趣而神奇的JavaScript的知識(shí)點(diǎn)。
如果你有任何問題,歡迎在留言區(qū)給我留言,如果你覺得有用或者有趣的話,請(qǐng)點(diǎn)贊我,關(guān)注我,并將它分享給你的開發(fā)者朋友,也許能夠幫助到他。
最后,感謝你的閱讀,編程愉快!
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

