我想在这里提一点指导。为此使用 JS Bin 。 整个问题是:" name"当用作VAR并在数组中时: --- console.log打印每个字母:
var word = "Hi";
var name = ["John","Suzette","Mari-Louise","Tinus","Hendrik","Koos","Elna","Elbie"];
// Greeting
greeter(word,name);
function greeter(str,arr){
var counter;
for(counter = 0;
counter < arr.length;
counter++) {
console.log(str + " " + arr[counter]);
}
}
输出
"Hi J"
"Hi o"
"Hi h"
"Hi n"
"Hi ,"
"Hi S"
"Hi u"
但是,将VAR更改为userName会产生正确的结果,..我无法找到任何对&#39; name&#39; 的引用是JS中的保留字,所以如果有人可以为我澄清这一点,它会粉碎。
var word = "Hi";
var userName = ["John","Suzette","Mari-Louise","Tinus","Hendrik","Koos","Elna","Elbie"];
// Greeting
greeter(word,userName);
function greeter(str,arr){
var counter;
for(counter = 0;
counter < arr.length;
counter++) {
console.log(str + " " + arr[counter]);
}
}
结果**
"Hi John"
"Hi Suzette"
"Hi Mari-Louise"
"Hi Tinus"
"Hi Hendrik"
"Hi Koos"
"Hi Elna"
"Hi Elbie"
答案 0 :(得分:0)
答案 1 :(得分:0)
如果进行调试,您会注意到执行代码时已经定义了name
。这是因为全局window
上下文具有name
属性,即字符串
当您尝试将["a", "b", "c"]
设置为此属性时,浏览器会将其转换为字符串,并变为"a,b,c"
。这就是为什么当你遍历它时,你会得到角色。
console.log(name); // it already exists
var name = ["a", "b", "c"]; // assigns window.name property, becomes a string
var nameqwe = ["a", "b", "c"]; // creates local variable
console.log(name);
console.log(nameqwe);