Javascript 为什么JS arrayTest中的[undefined]有效

Javascript 为什么JS arrayTest中的[undefined]有效,javascript,Javascript,最近我发现arrayTest[undefined]='something'和arrayTest[null]='something'在javascript中实际上是有效的。看看下面的代码 var arrayTest = []; var someText = 'someText'; arrayTest[undefined] = 'undefined'; arrayTest[null] = 'null'; arrayTest[someText] = 'someText'; // Reference

最近我发现arrayTest[undefined]='something'和arrayTest[null]='something'在javascript中实际上是有效的。看看下面的代码

var arrayTest = [];
var someText = 'someText';

arrayTest[undefined] = 'undefined';
arrayTest[null] = 'null';
arrayTest[someText] = 'someText';

// ReferenceError: someUndefinedText is not defined
//arrayTest[someUndefinedText] = 'someUndefinedText';

console.log(arrayTest);
//[ undefined: 'undefined', null: 'null', someText: 'someText' ]
有人对这段代码的有效性有逻辑解释吗。为什么试图通过显式地将其键设置为未定义来在数组中插入某些内容是有效的,而通过将其键设置为未定义的变量来在数组中插入某些内容是无效的


注:通过节点v0.12.2测试,未定义的变量(通常更容易被认为是未声明的变量)和具有未定义对象值的变量之间存在差异。(变量
undefined
的默认值为
undefined
对象)

尝试从前者读取将抛出一个引用错误,尝试从后者读取将给出
未定义的对象

使用方括号表示法访问属性时,必须传递字符串或可以转换为字符串的内容。
undefined
对象将转换为字符串
“undefined”
“+undefined===”undefined“


arrayTest
在这里基本不相关。错误源于试图读取变量
someUndefinedText
,以获取用作属性名的字符串。

未定义的变量(通常更容易被认为是未声明的变量)和具有
未定义对象值的变量之间存在差异。(变量
undefined
的默认值为
undefined
对象)

尝试从前者读取将抛出一个引用错误,尝试从后者读取将给出
未定义的对象

使用方括号表示法访问属性时,必须传递字符串或可以转换为字符串的内容。
undefined
对象将转换为字符串
“undefined”
“+undefined===”undefined“


arrayTest
在这里基本不相关。错误来自尝试读取变量
someUndefinedText
以获取用作属性名的字符串。

实际上您可以这样做

var arrayTest = [];
var someText = 'someText';

arrayTest[undefined] = 'undefined';
arrayTest[null] = 'null';
arrayTest[someText] = 'someText';

// ReferenceError: someUndefinedText is not defined
//arrayTest[someUndefinedReference] = 'someUndefinedText';

var bar; // test hold undefined value
arrayTest[bar] = 'foo'; // replace the value 'undefined' at index undefined by 'foo'
console.log(arrayTest);
这是因为在javascript中null和undefined是值。所以Javascript没有看到问题所在。
如果不声明变量,则与设置未定义或null不同。这是一个ReferenceError,在此引用中找不到任何值,并且没有引用!=未定义的

实际上您可以这样做

var arrayTest = [];
var someText = 'someText';

arrayTest[undefined] = 'undefined';
arrayTest[null] = 'null';
arrayTest[someText] = 'someText';

// ReferenceError: someUndefinedText is not defined
//arrayTest[someUndefinedReference] = 'someUndefinedText';

var bar; // test hold undefined value
arrayTest[bar] = 'foo'; // replace the value 'undefined' at index undefined by 'foo'
console.log(arrayTest);
这是因为在javascript中null和undefined是值。所以Javascript没有看到问题所在。
如果不声明变量,则与设置未定义或null不同。这是一个ReferenceError,在此引用中找不到任何值,并且没有引用!=未定义的

您确定这是从console.log()获得的输出吗?是的,您可以自己尝试,因为Firefox在控制台中显示了一个空数组
[]
。你确定
arrayTest
不是一个对象(
{}
)?@FrédéricHamidi:所有数组都是对象,但Firefox控制台可能不会显示数组的非数字属性。你确定这是从console.log()得到的输出吗?是的,你可以自己试试看,Firefox显示的数组是空的
[]
在控制台中。你确定
arrayTest
不是一个对象(
{}
)?@FrédéricHamidi:所有数组都是对象,但Firefox控制台可能不会显示数组的非数字属性。你确定“未定义的对象有一个toString()”,如果是,你能解释一下为什么未定义的.toString()不起作用吗?好的,现在你编辑它是真的。这是由于动态转换造成的。你确定“未定义的对象有一个toString()”吗?如果确定,你能解释一下为什么未定义的.toString()不起作用吗?好的,现在你编辑它是真的。这是由于动态转换。