简体   繁体   English

为什么一种代码有效,而另一种无效?

[英]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 . 在第一位, splitreversejoin都接受一个字符串,并返回一个新的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.

相关问题 为什么这些图标中的一个有效,而另一个无效? - Why does one of these icons work but the other does not? 为什么一段代码会覆盖另一段代码? - Why does one piece of code overrides the other? 为什么innerHTML 在这个实例中起作用,而在另一个实例中不起作用? - Why does innerHTML work in this one instance, but not in this other one? 为什么这一个Javascript(D3)块起作用,而另一个却不起作用? - Why does this one block of Javascript (D3) work, but not the other? 为什么Chrome间距只能在一个JS文件中起作用而不能在另一个JS文件中起作用? - Why does the Chrome spacing work in one JS file and not the other? Javascript - 为什么一个document.getElementById()工作而不是另一个? - Javascript — Why does one document.getElementById() work and not the other? 为什么一个计数器起作用而另一个计数器不起作用? (闭包?) - Why does one counter work and the other doesn't? (Closures?) 为什么一个JavaScript闭包工作而另一个没有? - Why does one JavaScript closure work and the other doesn't? 为什么一个AngularJS服务绑定起作用而另一个不起作用 - Why does one AngularJS service bind work but the other doesn't JavaScript正则表达式替换 - 为什么一个工作,但另一个不工作? - JavaScript regular expression replace - why does one work, but this other not?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM