javascript - 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() 可重用。
无法从以前的问题中找到答案,但如果它在某个地方,我很抱歉。
解决方案
您正在创建两个函数,但没有调用其中任何一个。例如,如果你让 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();
推荐阅读
- github - GitHub 分支保护 - 状态检查
- kotlin - 如何避免 MotionEvent.ACTION_CANCEL?
- android-studio - 如何使用 RemoteIntent 从智能手表在移动设备上启动配套应用程序
- java - 带有空格的横向数字金字塔 Java
- docker - GitLab docker executor 会打开登录 shell 吗?
- laravel - Laravel 8 - 如果一个规则适用,则显示所有验证规则
- arrays - 将 Pandas 列表大维度转换为 NP 数组
- machine-learning - 用于时间序列异常检测的训练/验证/测试拆分
- bash - 向 WSL 自动完成建议添加常用命令
- android - 添加了 Admob,现在收到 AudioManager 日志的垃圾邮件