javascript 简单的 js FOR 循环返回“未定义”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28665160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:20:35  来源:igfitidea点击:

Simple js FOR loop returning 'undefined'

javascriptvariablesfor-loop

提问by Uncle Slug

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

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

"undefinedHello World"
undefined

JS

JS

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

回答by thefourtheye

  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 = '';
    
  2. Also, note that, in this line

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

    ihas never been declared before. So, a new global variable iwill be created. You may not want that. So, just use varkeyword to declare the variable scoped to the current function, like this

    for (var i = 0; i < x.length; i++) {
    
  3. Apart from that, translate2is 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 undefinedin the question. To fix that, use returnstatement like this

    function translate2(x) {
        var newStr = "";
        for (var i = 0; i < x.length; i++) {
            newStr += x.charAt(i);
        }
        return newStr;
    }
    
  1. 在 JavaScript 中,如果一个变量没有显式初始化,默认情况下它会有undefined. 那不是字符串,而是语言的原始类型。您可以通过打印来检查

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

    所以,只需用一个空字符串初始化变量,就像这样

    var newStr = '';
    
  2. 另外,请注意,在这一行

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

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

    for (var i = 0; i < x.length; i++) {
    
  3. 除此之外,translate2是一个函数,当它被调用时,人们会期望它返回一些东西。但是您没有明确返回任何内容。因此,JavaScript 再次默认返回undefined. 这就是为什么你undefined在问题中得到第二个。要解决这个问题,请使用这样的return语句

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

回答by Ananth

You should first initialize the variable newStr.

您应该首先初始化变量 newStr。

var newStr = '';

Otherwise, newStr will be undefined and undefined + "asa" = "undefinedasa" in javascript. If you don't know what is undefined, check thisout.

否则,在 javascript 中 newStr 将是 undefined 和 undefined + "asa" = "undefinedasa"。如果您不知道什么是未定义的,请查看此内容

回答by Clemens Frahnow

newStr is undefined. Add

newStr 未定义。添加

var newStr = '';

So that you have

所以你有

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

回答by Abadis

The above answers are not correct. The console.log()will run before the loop finishes and that is why you get undefiend. You can find your answer here.

以上答案都不正确。该console.log()会在循环结束之前运行,这就是为什么你会得到undefiend。您可以在此处找到答案。

you have to think sync like this piece of code:

你必须像这段代码一样思考同步:

function delay() {
  return new Promise(resolve => setTimeout(resolve, 300));
}

async function delayedLog(item) {
  // notice that we can await a function
  // that returns a promise
  await delay();
  console.log(item);
}
async function processArray(array) {
  for (const item of array) {
    await delayedLog(item);
  }
  console.log('Done!');
}
processArray([1, 2, 3]);

this will give you 1,2,3,donewhich means the console.log is happening at the end of loop!

这将为您提供1,2,3,done这意味着 console.log 在循环结束时发生!