我正在尝试构建一个简单的邮政编码检查器,该程序将在其中检查用户输入的邮政编码是否与有效邮政编码列表匹配。问题是,我遇到一个错误,提示“无法读取未定义的属性'length'”。我究竟做错了什么?
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工作正常,请检查一下
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);