带参数的Javascript函数

esh*_*orn 1 javascript

我有两个变量是字符串:month1Digit1和month1Digit2.它们一起组成一个月的十进制数字(01-12),因此month1Digit1总是0或1,而month1Digit2可以是0以外的任何数字.现在我有几个,如month2Digit1,等等.想要一个可以从这些变量中确定月份名称的函数.但我不想为每个组编写一个单独的函数,因为它有不同的变量.从搜索周围看起来我需要用参数做一个函数,但我不确定这是如何工作的.我尝试了以下方法:

var month1Digit1 = "1";
var month1Digit2 = "2";

function getMonthName (month) {
    if (month == "1") { month = "January" }
    else if (month == "2") { month = "February" }
    else if (month == "3") { month = "March" }
    else if (month == "4") { month = "April" }
    else if (month == "5") { month = "May" }
    else if (month == "6") { month = "June" }
    else if (month == "7") { month = "July" }
    else if (month == "8") { month = "August" }
    else if (month == "9") { month = "September" }
    else if (month == "10") { month = "October" }
    else if (month == "11") { month = "November" }
    else if (month == "12") { month = "December" }
}

var orangemonth1 = month1Digit1 + month1Digit2;
getMonthName(orangemonth1);
orangedate = orangemonth1;
Run Code Online (Sandbox Code Playgroud)

既然如此,orangedate的值应该是'December',不是吗?但是当我运行它时,我得到"12"作为值.所以功能不起作用.我究竟做错了什么?

dje*_*lin 5

你抓到了一只红鲱鱼.

function foo(in) {
    in = 2;
}
var a = 1;
foo(a);
console.log(a); // prints 1
Run Code Online (Sandbox Code Playgroud)

您的问题远不及字符串连接或与字符串连接有关; 你理解得当.您需要了解Javascript是通过引用副本传递的,并且您正在更改引用的副本.请参阅此处:JavaScript是通过引用传递还是按值传递语言?