Javascript 数组与全局对象

Javascript 数组与全局对象,javascript,arrays,frontend,Javascript,Arrays,Frontend,我有这样的代码: var ui = ["one","two","three"]; ui.forEach(function(id) { ui[id] = "msg_all " + id }); console.dir(ui); 为什么当window.one==“msg_all one”您错误地使用了forEach函数,该函数的第一个参数是每次迭代的项,第二个参数是索引 var ui = ["one","two","three"]; ui.forEach(function(item,

我有这样的代码:

var ui = ["one","two","three"];
ui.forEach(function(id) 
{ 
   ui[id] = "msg_all " + id 
});
console.dir(ui);

为什么当window.one==“msg_all one”

您错误地使用了forEach函数,该函数的第一个参数是每次迭代的项,第二个参数是索引

var ui = ["one","two","three"];
ui.forEach(function(item, index) 
{ 
   ui[index] = "msg_all " + item 
});
console.dir(ui);

@gra窗口是所有javascript对象的基本范围,它自动“附加”到您定义的每个变量,除非在声明之前使用“var”,在本例中,变量的范围是局部的(这意味着它包含在父函数内,或者如果您在函数块外声明变量,它也是全局的)。此外,window被定义为常量,也就是说,您不能重新定义window对象(您将得到一个错误,称为“type error:Redclaration of const window”)。因为ui[id]等于一个示例ui[“一”]所以window.one等于该消息,而ui是一个索引为0 1 2的数组。你知道数组索引从零开始吗?你想实现什么?不,这是一个很好的示例。我知道第二个参数是索引,而第一个参数是索引项。但为什么我运行console.dir时会显示这些消息:[“一”、“二”、“三”][“一”、“二”、“三”长度:3 proto:Array[0]为什么?
id
不是整数,为什么直接在
ui
数组中将其用作索引?那么,为什么ui[“一”]=“msg\u all one”?var arr=[];arr[“x”]=“y”;console.log(arr.lenght)//0://但是:console.log(arr[]x“]/“y”为什么长度为0?