简体   繁体   English

在JavaScript函数中返回undefined

[英]undefined is returned in JavaScript function

When I call this function, sending for example: abc as the parameter, the function returns: undefinedcba. 当我调用此函数时,例如发送abc作为参数,该函数返回:undefinedcba。 I can't figure out why it's adding 'undefined' to my returned value. 我不知道为什么在返回值中添加了“未定义”。 I'm probably overlooking something obvious but I can't spot it. 我可能忽略了一些显而易见的事情,但我找不到它。 Thank you. 谢谢。

function FirstReverse(str) { 
    var str_arr1 = new Array();
    var ans = '';
    for(i=0; i < str.length; i++) {
        str_arr1.push(str.charAt(i));
    }
    for(j=str.length; j >= 0; j--) {
        ans += str_arr1[j];
    }
    return ans; 
}

Strings are 0-indexed. 字符串是0索引的。 str[str.length] does not exist. str[str.length]不存在。

j needs to start at str.length - 1 . j需要从str.length - 1开始。

Or, just return str_arr1.join(); 或者,只需return str_arr1.join();

The index of the string starts at 0, so string.length is always one number bigger than index of the last character in the string. 字符串的索引从0开始,因此string.length总是比字符串中最后一个字符的索引大一个数字。

In the second for loop, use 在第二个for循环中,使用

for(var j=str.length -1; j >= 0; j--) {

The error is in the second for statement. 错误在第二个for语句中。 See the solution: 查看解决方案:

function FirstReverse(str) { 
    var str_arr1 = new Array();
    var ans = '';
    for(i=0; i < str.length; i++) {
        str_arr1.push(str.charAt(i));
    }
    for(j=str.length-1; j >= 0; j--) {
        ans += str_arr1[j];
    }
    return ans;
}

Because when you pass 'abc' there are only 3 characters in it. 因为当您传递“ abc”时,其中只有3个字符。 So arrray str_arr have elements at index 0, 1 and 2. But you are looping for str.length ie for 3 times and str_arr[3] is not defined. 因此,arrray str_arr在索引0、1和2处具有元素。但是,您正在为str.length循环3次,并且str_arr[3]

You should do this, 你应该做这个,

function FirstReverse(str) {  
  var str_arr1 = new Array();
  var ans = '';
  for(i=0; i < str.length; i++) {
    str_arr1.push(str.charAt(i));
  }
  for(j=str.length-1; j >= 0; j--) {
    ans += str_arr1[j];
  }
  return ans;  
}

Looks like you want to reverse a string, which you can do in this javascript one liner 看起来您想反转一个字符串,可以在此javascript衬套中进行

function reverse(s){
    return s.split("").reverse().join("");
}

The reason you are getting an undefined is because your j starts with str.length , whereas it should be str.length-1. str_arr1[str.length] 得到未定义的原因是因为您的jstr.length开头,而它应该是str.length-1. str_arr1[str.length] str.length-1. str_arr1[str.length] is out of bounds and therefore will be undefined. str.length-1. str_arr1[str.length]超出范围,因此将是不确定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM