azl397985856 / fe-interview

宇宙最强的前端面试指南 (https://lucifer.ren/fe-interview)
Apache License 2.0
2.83k stars 260 forks source link

【每日一题】- 2020-05-11 - 如何让下面的代码返回true? #124

Closed azl397985856 closed 4 years ago

azl397985856 commented 4 years ago
'我' === '菜鸡' // true
chen00jian commented 4 years ago

面试 结果 = true

suukii commented 4 years ago

方法1:借用隐式类型转换

做法:改写 String 原型上的 valueOf 方法让它始终返回 菜狗,然后把相等式的一边换成 String 对象;

原理:== 比较对象和基本类型的时候,会尝试把对象转换成基本类型(一般先尝试调用 valueOf 再尝试调用 toString);

String.prototype.valueOf = () => '菜狗';
new String('我') == '菜狗' // true

不过题目中是全等,这种解法似乎有点偏离题意。

方法2:tagged function

想到的第二种方法是障眼法哈哈。

原理:

  1. 模板字符串可以用作函数调用;
  2. 根据 ASI (自动添加分号) 机制,以下代码是会合并成一行执行的;
(() => '菜狗')

`我` === '菜狗'
azl397985856 commented 4 years ago

@suukii 是不是也可以借助编译的力量

stale[bot] commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

lxhguard commented 4 years ago

你还在为自己不等于菜狗而发愁吗

console.log=e=>!e;
console.log('我' === '菜狗')