在Array中使用名称会在Firefox中产生不同的结果

时间:2016-09-02 03:09:34

标签: javascript arrays keyword reserved

我想在这里提一点指导。为此使用 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"

2 个答案:

答案 0 :(得分:0)

哦但是&#39;名字&#39;保留:

http://www.w3schools.com/js/js_reserved.asp

查看JavaScript对象,属性和方法

答案 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);