JS判斷元素是否在數組內

1、jQueryjavascript

若是是用JQuery的話,能夠用inArray()函數:java

jquery inarray()函數詳解
jquery.inarray(value,array)
肯定第一個參數在數組中的位置(若是沒有找到則返回 -1 )。

determine the index of the first parameter in the array (-1 if not found).
返回值
jquery
參數
value (any) : 用於在數組中查找是否存在
array (array) : 待處理數組。jquery

用法爲:數組

 

[javascript]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. $.inArray(value, array)  

 

 

2、本身寫函數函數

 

[javascript]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. function contains(arr, obj) {  
  2.     var i = arr.length;  
  3.     while (i--) {  
  4.         if (arr[i] === obj) {  
  5.             return true;  
  6.         }  
  7.     }  
  8.     return false;  
  9. }  

 

用法爲:this

 

[javascript]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. var arr = new Array(1, 2, 3);  
  2. contains(arr, 2);//返回true  
  3. contains(arr, 4);//返回false  

 

 


3、給Array增長一個函數spa

 

[javascript]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. Array.prototype.contains = function (obj) {  
  2.     var i = this.length;  
  3.     while (i--) {  
  4.         if (this[i] === obj) {  
  5.             return true;  
  6.         }  
  7.     }  
  8.     return false;  
  9. }  

使用方法:.net

 

 

[javascript]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. [1, 2, 3].contains(2); //返回true  
  2. [1, 2, 3].contains('2'); //返回false  



4、使用indexOfprototype

 

可是有個問題是IndexOf在某些IE版本中是不兼容的,能夠用下面的方法:code

 

[javascript]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. if (!Array.indexOf) {  
  2.     Array.prototype.indexOf = function (obj) {  
  3.         for (var i = 0; i < this.length; i++) {  
  4.             if (this[i] == obj) {  
  5.                 return i;  
  6.             }  
  7.         }  
  8.         return -1;  
  9.     }  
  10. }  


先判斷Array是否有indexOf方法,若是沒有就擴展出此方法。

 

因此上面代碼要寫在使用indexOf方法的代碼以前:

 

[javascript]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
    1. var arr = new Array('1', '2', '3');  
    2. if (!Array.indexOf) {  
    3.     Array.prototype.indexOf = function (obj) {  
    4.         for (var i = 0; i < this.length; i++) {  
    5.             if (this[i] == obj) {  
    6.                 return i;  
    7.             }  
    8.         }  
    9.         return -1;  
    10.     }  
    11. }  
    12. var index = arr.indexOf('1');//爲index賦值爲0  
相關文章
相關標籤/搜索