close

最近,我遇到了一些奇怪而有趣的面試題,它們與常規問題不同,這些面試問題看起來很簡單,但它們會測試你對 JavaScript 的透徹理解,今天我就來跟大家分享5個神奇的JavaScript知識點,看看你能答對幾個?

現在,我們就馬上開始吧。

1. 「x !== x」可以返回true嗎?

輸出「hello fatfish」的「x」值應該是多少?

const x = ? // Please fill in the value of "x?if (x !== x) { console.log('hello fatfish')}

太奇妙了,是否存在不等於自身的值?但是,JavaScript 中有一個值 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嗎?

好的,當我們過濾掉「NaN」時,還有什麼值可以讓一個值不等於自己呢?

const x = ? // Please fill in the value of "x?if(!isNaN(x) && x !== x) { console.log('hello fatfish')}

也許你知道「object.Defineproperty」,它可以幫助我們解決這個問題。

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」?

這個問題可能並不容易,但只要你了解 JavaScript,你就會知道「Number.MAX_SAFE_INTEGER 常量代表 JavaScript 中的最大安全整數 (²⁵³ — 1)。」(這個解釋來自 MDN)

constx=?//Pleasefillinthevalueof"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')}

雖然,看起來不太可能,但是一個值怎麼可能大於它自己呢?但是,我們可以使用「Symbol.toPrimitive」功能來完成問題。

const x = { // Please fill in the value of "x? value: 1, [ Symbol.toPrimitive ] () { console.log('x', this.value) return --this.value }}if (x > x) { console.log('hello fatfish')}

哦,真是太精彩了!

5. typeof x === 『undefined』 && x.length > 0 ?

constx=?//Pleasefillinthevalueof"x?if(typeof x === 'undefined' && x.length > 0) { console.log('hello fatfish')}

我不得不承認 JavaScript 是一門了不起的語言。除了 undefined 本身,還有什麼值可以讓 typeof x === undefined」 為真呢?

答案是文檔。All 一個 HTMLAllCollection,它包含文檔中的每個元素(來自 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個非常有趣而神奇的JavaScript的知識點。

如果你有任何問題,歡迎在留言區給我留言,如果你覺得有用或者有趣的話,請點讚我,關注我,並將它分享給你的開發者朋友,也許能夠幫助到他。

最後,感謝你的閱讀,編程愉快!

學習更多技能

請點擊下方公眾號


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 鑽石舞台 的頭像
    鑽石舞台

    鑽石舞台

    鑽石舞台 發表在 痞客邦 留言(0) 人氣()