简单的js FOR循环返回“未定义" [英] Simple js FOR loop returning 'undefined'

查看:272
本文介绍了简单的js FOR循环返回“未定义"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定在这里我在做什么错;变量newStr应该只返回"Hello World",但我却得到了它:

Not sure what I'm doing wrong here; the variable newStr should just return "Hello World", but I'm getting this instead:

"undefinedHello World"
undefined

JS

function translate2(x){
  var newStr;
  x = "Hello World";
  for(i=0; i<x.length; i++) {
    newStr+=x.charAt(i);
  }
  console.log(newStr);
}

推荐答案

  1. 在JavaScript中,如果未明确初始化变量,则默认情况下它将具有

  1. In JavaScript, if a variable is not initialized explicitly, it will by default have undefined. That is not a string but a primitive type of the Language. You can check that by printing it

var newStr;
console.log(newStr);
// undefined
console.log(newStr + "thefourtheye");
// undefinedthefourtheye

因此,只需使用一个空字符串初始化变量,就像这样

So, just initialize the variable with an empty string, like this

var newStr = '';

  • 另外,请注意,在这一行

  • Also, note that, in this line

    for(i=0; i < x.length; i++) {
    

    i以前从未声明过.因此,将创建一个新的全局变量i.您可能不想要那样.因此,只需使用var关键字声明作用域为当前函数的变量,就像这样

    i has never been declared before. So, a new global variable i will be created. You may not want that. So, just use var keyword to declare the variable scoped to the current function, like this

    for (var i = 0; i < x.length; i++) {
    

  • 除此之外,translate2是一个函数,当调用它时,人们希望它返回一些东西.但是您没有明确返回任何内容.因此,同样,JavaScript默认情况下会返回undefined.这就是为什么您在问题中得到第二个undefined的原因.要解决此问题,请使用像这样的return语句

  • Apart from that, translate2 is a function and when it is invoked, one would expect it to return something. But you are not returning anything explicitly. So, again, JavaScript, by default, returns undefined. That is why you are getting the second undefined in the question. To fix that, use return statement like this

    function translate2(x) {
        var newStr = "";
        for (var i = 0; i < x.length; i++) {
            newStr += x.charAt(i);
        }
        return newStr;
    }
    

  • 这篇关于简单的js FOR循环返回“未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆