2015-06-20 41 views
1

我似乎無法獲得此代碼工作(即,讓isInArray(userZipCode,chicagoZipCodes)返回true問題與檢查如果輸入值等於在數組中的值

var chicagoZipCodes = [ 60018, 60068, 60176, 60601, 60602, 60603, 60604, 60605, 60606, 60607, 60608, 60609, 
          60610, 60611, 60612, 60613, 60614, 60615, 60616, 60617, 60618, 60619, 60620, 60621, 
          60622, 60623, 60624, 60625, 60626, 60628, 60630, 60631, 60632, 60634, 60636, 60637, 
          60639, 60640, 60641, 60642, 60643, 60644, 60645, 60646, 60647, 60649, 60651, 60652, 
          60653, 60654, 60655, 60656, 60657, 60659, 60660, 60661, 60706, 60707, 60714 ] 

    function isInArray(value, array) { 
    return array.indexOf(value) !== -1 
    } 

    elem.bind('change', function(e) { 
    userZipCode = $('#zipCode').val(); 

    alert(isInArray(userZipCode,chicagoZipCodes)); 

    if (!(isInArray(userZipCode, chicagoZipCodes)) && (userZipCode.length > 4)) { 
     // success 
     alert("Sorry, that is not a Chicago area zip code! :("); 
     e.stopImmediatePropagation(); 
    } 
    }) 
+0

感謝所有的快速回答傢伙!看起來像'parseInt'是我正在尋找的 - 快速簡單的解決方案 – ksy

+0

請注意,使用'parseInt'時應注意:http://stackoverflow.com/questions/4090518/string-to-int-use -parseint-or-number –

+0

謝謝你的提問Jason – ksy

回答

4

像你比較數字使用的indexOf()函數之前和字符串

function isInArray(value, array) { 
     return array.indexOf(parseInt(value,10)) !== -1 
} 
+1

爲了給這個答案添加上下文,我編輯了問題在'isInArray'中包含'return',但答案是添加了'parseInt' – ksy

1

解析您的$( '#ZIPCODE')。VAL()。

return array.indexOf(parseInt(value); 
1

從DOM返回的所有值都是字符串,因此您需要將它們轉換爲數字。你可以用幾種方法來做到這一點,但最直接的做法是使用Number作爲函數而不是構造函數。

var chicagoZipCodes = [60018, 60068, 60176, 60601, 60602, 60603, 60604, 60605, 60606, 60607, 60608, 60609, 
    60610, 60611, 60612, 60613, 60614, 60615, 60616, 60617, 60618, 60619, 60620, 60621, 
    60622, 60623, 60624, 60625, 60626, 60628, 60630, 60631, 60632, 60634, 60636, 60637, 
    60639, 60640, 60641, 60642, 60643, 60644, 60645, 60646, 60647, 60649, 60651, 60652, 
    60653, 60654, 60655, 60656, 60657, 60659, 60660, 60661, 60706, 60707, 60714 
] 

function isInArray(value, array) { 
    return array.indexOf(value) !== -1 
} 

elem.bind('change', function(e) { 
    // All values returned from the DOM are strings 
    // so we need to convert them to a number 
    userZipCode = Number($('#zipCode').val()); 

    alert(isInArray(userZipCode, chicagoZipCodes)); 

    // Check length first since all Chicago zips listed are greater than 4 digits 
    // Saves the more expensive check of searching the array for 
    // only zips that are greater than 4 
    if ((userZipCode.length > 4) && !(isInArray(userZipCode, chicagoZipCodes))) { 
    // success 
    alert("Sorry, that is not a Chicago area zip code! :("); 
    e.stopImmediatePropagation(); 
    } 
}); 
相關問題