如果用js实现a变量为undefined,但是a.b.c的值为1?-灵析社区

楠楠不难难

有没有什么办法可以做到如下 console.log(a); // undefined console.log(a.b); // undefined console.log(a.b.c); // 1

阅读量:261

点赞量:15

问AI
可能不符合题意,但是确实是 "undefined" const a = "undefined"; Object.defineProperties(String.prototype, { b: { value: "undefined" }, c: { value: 1 }, }); console.log(a); // undefined console.log(a.b); // undefined console.log(a.b.c); // 1 补充,"undefined" 不是对象,而 "Object.defineProperty" 和 "Proxy" 都只能用于对象,所以如果 "a" 真是 "undefined" 是不可能实现的; 如果自定义一个对象,让 "console.log" 输出这个对象的时候打印 "undefined",不同浏览器的 "console.log" 实现不同,而且不一定会调用 "toString()" 或者 "valueOf()": «Console API in FF calls "toString()" on the argument only if the argument type is not one of "{ undefined, null, object, set, map }" types. It doesn't always call "toString()" or "valueOf()" methods.»