[英]Why does one code work, but not the other?
The question I am answering: Complete the solution so that it reverses the string value passed into it. 我正在回答的问题:完成解决方案,以便它反转传递给它的字符串值。
I answered this: 我回答了这个:
function solution(str){
str.split("").reverse().join("");
return(str);
}
but it didnt work 但这没用
Instead, this was the correct solution: 相反,这是正确的解决方案:
function solution(str){
return str.split("").reverse().join("");
}
why is it that the second solution works but not the first? 为什么第二个解决方案有效而第一个解决方案无效?
In the first one, the variable str
doesn't get redefined, so you end up returning the original value. 在第一个变量中,不会重新定义变量
str
,因此最终将返回原始值。 You would need to do this: 您需要这样做:
function solution(str){
str = str.split("").reverse().join("");
return(str);
}
Strings are immutable. 字符串是不可变的。 Any method that "alters" a String is really returning the new version of the string for you to use.
任何“改变”字符串的方法实际上都会返回该字符串的新版本供您使用。
In the first bit, split
, reverse
and join
are all taking a string, and returning a new string . 在第一位,
split
, reverse
和join
都接受一个字符串,并返回一个新的string 。 They don't modify str
. 他们不修改
str
。 You're having those functions do work, throwing away the result of the functions, then returning the original str
. 您正在使那些函数起作用,丢弃这些函数的结果,然后返回原始的
str
。
The second version works because join
returns a new joined String, then that new string is given to return
to be returned. 第二个版本有效,因为
join
返回一个新的连接的String,然后将该新字符串return
以返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.