简体   繁体   English

为什么object [undefined]在javascript中不起作用?

[英]Why doesn't object[undefined] work in javascript?

I thought all values in between [ ] were converted to strings, why isn't undefined converted to "undefined" ? 我以为[]之间的所有值都转换为字符串,为什么不将undefined转换为"undefined"

var a={};
a[undefined];
Object.keys(a).length===0

I think you've basically found an edge case. 我认为您基本上已经找到了一个极端案例。

If I had a variable a that was undefined, calling myObject[a] should also return undefined , like you're referencing an object property that isn't there. 如果我有一个未定义的变量a ,则调用myObject[a]也应返回undefined ,就像您引用的对象属性不存在一样。 Hardcoding undefined probably is equivalent to the interpreter as using an undefined variable. 硬编码undefined可能与使用未定义变量的解释器等效。

You're assumption that all values between [] are converted to strings is incorrect. 您假设[]之间的所有值都转换为字符串不正确。

That being said, what you're doing would work, if you actually assigned anything to your undefined key, but you aren't. 话虽这么说,你在做什么工作 ,如果实际分配到任何你undefined钥匙,但你不是。

var a = {};
a[undefined] = 1;
Object.keys(a).length === 1;

Or even 甚至

var a = {};
a[undefined] = undefined;
Object.keys(a).length === 1;

If you don't assign a value to the key in a hash, the key is not retained. 如果您没有为哈希中的键分配值,则不会保留键。

EDIT 编辑

It's interesting how this language works. 这种语言的工作方式很有趣。 When you declare a variable without a value, JS initializes it with a value of undefined 当您声明没有值的变量时,JS会使用undefined的值对其进行初始化

var x;
console.log(x); //undefined

But when you attempt to declare a key on an object without assigning it to a value, then it is not initialized with a value of undefined ; 但是,当您尝试在对象上声明键而不将其分配给值时,则不会使用undefined值对其进行初始化;

var x = {};
x[1];
Object.keys(x).length === 0;

Also, just for fun, it should be easy to see from the above that the following is true: 另外,仅出于娱乐目的,从上面可以很容易看出以下事实:

var x; //initializes to undefined
var y = {};
y[undefined] = x;
Object.keys(y).length === 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM