我编写了一个函数,在输入邮政编码时调用zipcode API来检索地址。 (注意:这是荷兰语申请,荷兰语邮政编码由4个数字和2个字母组成。)
这是功能:
function zipcodeApiCall(zipcodeNum, zipcodeAlfa)
{
console.log(zipcodeNum);
if(zipcodeNum.length == 4 && zipcodeAlfa.length == 2)
{
//some code to call the API that returns some data
}
}
//Call the function
var zipcodeNum = $("#zipcodeNum").val(); //Retrieve val from input field
var result = zipcodeApiCall(zipcodeNum, 'KK');
问题是我在检索zipcodeNum长度时遇到了zipcodeNum未定义的错误。输出:
console.log(zipcodeNum);
邮政编码1312的是两行:
1312
undefined
这给了我错误'未捕获的TypeError:无法读取未定义'的属性'长度'。为什么会这样?
当我在函数中检索zipcodeNum的值时,还有一点奇怪:
function zipcodeApiCall()
{
var zipcodeNum = $("#zipcodeNum").val(); //Retrieve val from input field
var zipcodeAlfa = 'KK';
console.log(zipcodeNum);
if(zipcodeNum.length == 4 && zipcodeAlfa.length == 2)
{
//some code to call the API that returns some data
}
}
var result = zipcodeApiCall();
代码执行正常,我没有任何错误。