zl程序教程

您现在的位置是:首页 >  Java

当前栏目

五个你可能不知道的神奇JavaScript知识点!

2023-02-19 12:24:13 时间

最近,我遇到了一些奇怪而有趣的面试题,它们与常规问题不同,这些面试问题看起来很简单,但它们会测试你对 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)

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')}

虽然,看起来不太可能,但是一个值怎么可能大于它自己呢?但是,我们可以使用“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 ?

const x = ? // Please fill in the value of "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的知识点。

如果你有任何问题,欢迎在留言区给我留言,如果你觉得有用或者有趣的话,请点赞我,关注我,并将它分享给你的开发者朋友,也许能够帮助到他。

最后,感谢你的阅读,编程愉快!