简体   繁体   English

为什么函数必须具有等于自身总和的变量和一个空字符串

[英]Why must functions have variables that equal to the sum of itself and an empty string

In this code:在这段代码中:


function reverse_a_number(n)
{
    n = n + "";
    return n.split("").reverse().join("");
}
console.log(Number(reverse_a_number(32243))); 

Its function is supposed to reverse any number.它的 function 应该反转任何数字。

Why must "n" be equal to ' n + "" '?为什么“n”必须等于'n +“”'?

In the return statement why must the split and join methods have an empty string and not reverse?在 return 语句中,为什么 split 和 join 方法必须有一个空字符串而不是反转?

Why can't the code be like the one written below (I know it would read error, but I want understand why)?为什么代码不能像下面写的那样(我知道它会读取错误,但我想了解原因)?

function reverse_a_number(n)
{
return n.split().reverse().join();
}

console.log(Number(reverse_a_number(32243))); 

Why must n be equal to n + "" ?为什么n必须等于n + ""

n = n + "";

is equivalent to相当于

n = String(n);

This is needed because split() is a string method, it doesn't work with numbers.这是必需的,因为split()是一个字符串方法,它不适用于数字。

In the return statement why must the split and join methods have an empty string and not reverse?在 return 语句中,为什么 split 和 join 方法必须有一个空字符串而不是反转?

You have to give a separator to split() .你必须给split()一个分隔符。 Using an empty string means to turn each character into an element of the result array.使用空字符串意味着将每个字符转换为结果数组的一个元素。 If you omit the separator, the default is to put the entire string into a single array element.如果省略分隔符,则默认将整个字符串放入单个数组元素中。

For join() , the default separator is , .对于join() ,默认分隔符是, So if you left this out you would get '3,4,2,2,3' instead of '34223' .因此,如果您将其省略,您将得到'3,4,2,2,3'而不是'34223'

reverse() doesn't have any parameters. reverse()没有任何参数。 It simply reverses the array that it's called on, there are no options.它只是反转它被调用的数组,没有选项。

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

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