对于带有数组的循环,不打印正确的结果

时间:2017-02-09 06:42:40

标签: javascript php jquery angularjs

js上的新内容,代码如下。在这里,我无法打印出正确的结果。我认为+ "names[i]"这部分代码存在问题。

var names = ["aha","mk", "jk","hk","fhf"];
for (i=1;i<=names.length;i++){
    console.log("I know someone called "+ "names[i]");
    }

6 个答案:

答案 0 :(得分:1)

请勿在引号names[i]中使用expression来提供您的价值

您可以使用es6模板字符串

var names = ["aha","mk", "jk","hk","fhf"];
   for (i=0;i<=names.length-1;i++){
       console.log(`I know someone called ${names[i]}`);
    }

答案 1 :(得分:0)

var names = ["aha","mk", "jk","hk","fhf"];
for (i=1;i<=names.length;i++){
    console.log("I know someone called "+ names[i]);
    }

names [i]已经是一个字符串。

答案 2 :(得分:0)

忽略名称[i]周围的引号。 它应该是:

var names = ["aha","mk", "jk","hk","fhf"];
for (i=1;i<=names.length;i++){
    console.log("I know someone called "+ names[i]);
}

答案 3 :(得分:0)

请检查名称[i]是否应该保留双引号并将i值更改为0

 var names = ["aha","mk", "jk","hk","fhf"];
 for (i=0;i<=names.length;i++)
 {
      console.log("I know someone called "+ names[i]);
 }

答案 4 :(得分:-1)

  • 第一:就像所有人一直在说的那样,你不要将names[i]置于双引号内,因为它是对已定义变量的引用。

  • 第二次:** ** for循环中的**声明为i<=names.length,但应为i<names.length。你的方式会一直走到6,这太高了。

  • THIRD :除了第二个错误之外,您还必须将names[i]更改为names[i--],因为i<names.length仍会达到5,而且也是很高的数字开头。

答案 5 :(得分:-1)

我认为这是正常的 你需要删除=符号并设置i = 0

var names = ["aha","mk", "jk","hk","fhf"];
        for (i=0;i<names.length;i++){
        console.log("I know someone called "+ names[i]);
    }