0

我想在这里得到一点指导。为此使用JS Bin。这里的整个问题是:“名称”用作 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 会产生正确的结果,..我在 JS 中找不到任何对“name”作为保留字的引用,所以如果有人可以为我澄清这一点,那就太棒了。

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"
4

2 回答 2

0

哦,但“名称”是保留的:

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

查看 JavaScript 对象、属性和方法

于 2016-09-02T03:12:20.413 回答
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);

于 2016-09-02T03:17:57.893 回答