[英]Iterating on my array in JS but I'm getting a "Cannot read property 'length' of undefined" error
I am trying to build a simple zip code checker where the program will check a user's input zip code matches a list of valid zip codes.我正在尝试构建一个简单的邮政编码检查器,该程序将检查用户输入的邮政编码是否与有效邮政编码列表相匹配。 The issue is, I am running into an error that says "Cannot read property 'length' of undefined".
问题是,我遇到了一个错误,提示“无法读取未定义的属性‘长度’”。 What am I doing wrong?
我究竟做错了什么?
let validZips = [12345, 78910]; let zip = document.getElementById("zipCode").value; const checkCode = (zip, validZips) => { for (let i = 0; i < validZips.length; i++) { if (zip !== validZips[i]) { alert("out of service area") } } }
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <body> <div class="container"> <label for="zipCode">Zip Code</label> <br> <input type="text" placeholder="Enter a zipcode" id="zipCode"> <br> <button type="submit" onclick="checkCode()"> Check Zip Code</button> </div> </body> </html>
validZips.length works fine, check this out validZips.length 工作正常,看看这个
let validZips = [12345, 78910]; const checkCode = (zip, validZips) => { for (let i = 0; i < validZips.length; i++) { if (zip !== validZips[i]) { console.log("out of service area, ", validZips[i]); } } } checkCode(1234, validZips);
User "barzin.A" suggested that the code wasn't executing because the array wasn't in the function scope.用户“barzin.A”建议代码没有执行,因为数组不在函数范围内。 I defined the array in the scope of the function and everything worked as intended.
我在函数范围内定义了数组,一切都按预期工作。 Here's the solution code:
这是解决方案代码:
let zip = document.getElementById("zipCode").value;
const checkCode = (validZips,zip) =>
{
validZips = [12345,67891];
for(let i=0; i < validZips.length; i++){
if (zip !== validZips[i]) {
alert("out of service area")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.