javascript - 使用 startsWith 函数识别邮政编码的前三位
问题描述
我正在尝试使用该startsWith
功能来识别输入的邮政编码的前三位。我正在测试的邮政编码是 44646。当我添加它时,它应该被识别为数组446
中的字段之一。str
else 语句正在被识别并正在阅读。
有谁看到我做错了什么?
$('#salesforce_submit').change(function () {
zipVal = $('#zip').val();
var zipVals = [ 44030 , 44048 , 44082 , 44003 , 44093 , 44076 , 44062 , 44021 , 44046 , 44099 , 44032 , 44047 , 44010 , 44057 , 44086 , 44064 , 44024 , 44023 , 44065 , 44022 , 44072 , 44040 , 44143 , 44094 , 44139 , 44146 , 44128 , 44105 , 44122 , 44124 , 44121 , 44117 , 44108 , 44110 , 44103 , 44106 , 44118 , 44120 , 44104 , 44114 , 44127 , 44125 , 44131 , 44134 , 44129 , 44130 , 44144 , 44109 , 44115 , 44136 , 44133 , 44147 , 44141 , 44067 , 44056 , 44087 , 44195 ];
var str = [ 442 , 443 , 444 , 445 , 446 , 447 , 437 , 438 , 439 , 457 , 434 , 435 , 436 , 164 , 165 , 163 , 161 , 160 , 162 , 150 , 151 , 152 , 156 , 153 , 154 , 585 , 716 , 142 ];
if ( zipVal.startsWith( +str ) ) {
contains = 'Contain in place';
$('#show').text(contains);
} else {
contains = 'Contain not in place';
$('#show').text(contains);
}
console.log(contains);
if ( zipVals.includes( +zipVal ) ) {
zipAssign = 'AB';
} else {
zipAssign = '';
}
console.log(zipAssign);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="salesforce_submit">
<div><input id="zip" placeholder="Zip/Postal Code*" class="input block" maxlength="6" name="zip" type="text" pattern= "[0-9]{5}"></div>
<p id="show"></p>
</form>
解决方案
+str
表达式为您提供 NaN,因为您将数组转换为数字。因此,尝试以这种方式检查:
if (str.find(num => zipVal.startsWith(num)) !== undefined;) ...
同样应该为if ( zipVals.includes( +zipVal ) ) {
推荐阅读
- amazon-route53 - Route 53 管理的 DNS 中的问题
- swiftui - SwiftUI 禁用列表边框 iOS 14
- html - 砌体框布局无法根据使用 CSS 的文本工作
- linux - centos 的自定义命令
- python - 卷积神经网络中的输入和输出形状
- bash - 为什么有些脚本与 #! /bin/sh 和一些带有 #! /bin/ksh 在 Solaris 机器上?
- git - 如何解释 git reset --soft && git checkout 的行为
- excel - Access/Excel/VBA 中的日期到 Weeknum
- flutter - FirebaseDynamicLinks getInitialLink() 多次触发
- google-apps-script - GmailApp.getInboxThreads() 跳过电子邮件