首页 > 解决方案 > javascript - 调用函数不传递参数

问题描述

扯掉我的头发!!

我有以下类似的代码片段:

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() 可重用。

无法从以前的问题中找到答案,但如果它在某个地方,我很抱歉。

标签: javascriptparametersarguments

解决方案


您正在创建两个函数,但没有调用其中任何一个。例如,如果你让 checkCountry() 自动执行或调用它,你就会得到你想要的。

checkCountry();

或者

(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();

推荐阅读