我在驗證腳本中遇到了一個問題,以檢查澳大利亞郵政編碼。 它似乎沒有通過包含郵編值的多維數組遞增。javascript驗證多維數組中多個範圍的值
這裏的功能:
function validateAustralia(postcode, ranges) {
for (var i = 0; i < ranges.length; i++) {
console.log(i);
//returns only 0, when it should return 0, 1, 2.
console.log("postcode: " + postcode + " " + "ranges: " + ranges);
//returns postcode: 2000 ranges: 200,299,2600,2618,2900,2920
console.log("ranges - low: " + ranges[2][0] + " " + "ranges - high: " + ranges[2][1]);
//returns ranges - low: 2900 ranges - high: 2920
if (postcode >= ranges[i][0] && (postcode <= ranges[i][1])) {
valid = true;
//confirmation();
//break;
} else {
inelegible();
return false;
}
}
}
對於新南威爾士州,例如
ranges = [ [1000, 2599], [2619, 2898], [2921, 2999] ];
它只有返回1000和2599 - 這是範圍[0] [0]和範圍[0 [1] 因此,有人輸入Dubbo(位於新南威爾士州)的郵政編碼被裁定爲無效,因爲其郵編-2830不在1000和2599之間。
jQuery's $ .each()正確地遍歷第一個數組,但我不確定如何從第二個數組中獲取值。
編輯: 好的,所以這是一個深夜,而我是盲目的。 小二郎的答案大部分都在下面,這裏的一位朋友也指出了這一點:我在第一次運行後終止了迭代。 我移動了,如果else循環迭代,只是測試如果郵政編碼是在範圍內。如果是,它是有效的。 然後,如果有效=真我打電話確認功能和一切好:
function validateAustralia(postcode, ranges) {
for (var i = 0; i < ranges.length; i++) {
console.log(i);
// returns 0, 1, 2 ...
console.log("postcode: " + postcode + " " + "ranges: " + ranges);
// for Dubbo (2830), for example, returns postcode: 2830 ranges: 1000,2599,2619,2898,2921,2999
console.log("ranges - low: " + ranges[i][0] + " " + "ranges - high: " + ranges[i][1]);
// returns ranges - low: 1000 ranges - high: 2599,
// ranges - low: 2619 ranges - high: 2898, ...
if (postcode >= ranges[i][0] && (postcode <= ranges[i][1])) {
valid = true;
// alert("valid =" + valid);
}
if (valid === true) {
confirmation();
// all good
} else {
inelegible();
// Sorry, mate
}
}
}
因爲我是新來的,(長時間的傾聽者,第一次調用者),我不能回答我的問題,但基本上就是這樣。
這裏的HTML和@nnnnnn和其他人誰希望看到調用函數: 用戶從選擇
<select id="states" name="states">
<option selected="" value="">Please choose ...</option>
<optgroup label="Australia" id="australia">
<option value="act">Australian Capital Territory </option>
<option value="nsw">New South Wales </option>
<!-- ...and so on for the rest of the states -->
選擇自己的狀態並輸入他們的郵政編碼到一個文本框
<input id="postcode" name="postcode" type="text" maxlength="4" />
我得到正是如此
postcode = $('#postcode').val();
和檢查抗拒着一系列郵政編碼值
function checkAustralia(state, postcode, ranges) {
// has to be in the range of values
switch (state) {
//Australian states
//match the whole postcode
//postcodes with a leading '0' are validated as whole numbers without the '0'
case 'act':
ranges = [ [200, 299], [2600, 2618], [2900, 2920] ];
validateAustralia(postcode, ranges);
break;
case 'nsw':
ranges = [ [1000, 2599], [2619, 2898], [2921, 2999] ];
validateAustralia(postcode, ranges);
break;
// ...and so on for the rest of the states
如果您記錄正確範圍,會發生什麼情況?這是你所期待的嗎?如果你只能通過一次迭代,可能範圍不是很好的形成? – thescientist
1.您可以發佈調用您的函數的代碼嗎?你已經給出了一個NSW範圍的例子,但並不完全如此。 2.這種事情不應該被驗證服務器端嗎? – nnnnnn
謝謝你們,我想我現在已經報道了。 @thescientist它是返回錯誤,停止迭代。 @nnnnnn 1.出於教育目的,我將發佈調用函數2。我更喜歡它在服務器端完成,但這就是我們必須處理的:) –