javascript-调用函数不传递参数

时间:2018-06-26 15:20:11

标签: javascript parameters arguments

把头发撕掉!

我有以下与此类似的代码段:

function checkCountry(countrycode)
{
    //var countrycode="GB";
    var country = getCountry(countrycode);
    alert("checkCountry: country = "+country);


}

function getCountry(countrycode)
{
    var len = arguments.length;
    alert("getCountry: len = "+len);
    alert("getCountry: countrycode = "+countrycode);
    return countrycode;
}

checkCountry()是从另一个js函数调用的。

问题是,无论我从checkCountry()传递给getCountry(),getCountry()中的国家/地区代码始终是一个空字符串。

我尝试传递字符串文字,即“ GB”;我试过更改getCountry()函数名称;我已经将getCountry()移到了与checkCountry()相同的js文件中。

getCountry()中的arguments.length似乎是来自警报的空字符串,显示'getCountry:len =';我以为会是0或“未定义”。

当我将getCountry()代码移到checkCountry()时,它起作用了!但是我需要/想要getCountry()可重用。

找不到以前的问题的答案,但是如果它在某个地方,我深表歉意。

2 个答案:

答案 0 :(得分:0)

您正在创建两个函数,但未调用其中任何一个。例如,如果使checkCountry()自动执行或调用它,您将获得所需的内容。

checkCountry();

OR

(function checkCountry()
{
    var countrycode="GB";
    var country = getCountry(countrycode);
})();

您可以这样实现自己的目标:

var x = {};
x.checkCountry = function(){
    var countrycode="GB";
    var country = getCountry(countrycode);
}

x.getCountry = function(countrycode){
    var len = arguments.length;
    alert("getCountry: len = "+len);
    alert("getCountry: countrycode = "+countrycode);

};
x.checkCountry();

答案 1 :(得分:0)

代码没有错:

function checkCountry()
{
    var countrycode="GB";
    var country = getCountry(countrycode);
    alert("checkCountry: country = "+country);
}

function getCountry(countrycode)
{
    var len = arguments.length;
    alert("getCountry: len = "+len);
    alert("getCountry: countrycode = "+countrycode);
    return countrycode;
}

您可以检查项目/环境中是否还有其他问题。 有什么方法可以在项目的其他地方重复/替换功能名称。 您可以在函数的每个步骤中设置警报,然后调用checkCountry()并查看发生错误/丢失的地方。

Ps-在我的环境中,我复制了两个函数,并调用了 checkCountry()函数(例如,单击按钮)。 每次我收到3个警报,显示以下值:

getCountry: len = 1
getCountry: countrycode = GB
checkCountry: country = GB

所以问题出在其他地方。