How to check if array element exists or not in javascript?

前端 未结 18 1687
粉色の甜心
粉色の甜心 2020-12-07 10:05

I am working with Titanium, my code looks like this:

var currentData = new Array();

if(currentData[index]!==\"\"||currentData[index]!==null||currentData[ind         


        
相关标签:
18条回答
  • 2020-12-07 10:33

    This is exactly what the in operator is for. Use it like this:

    if (index in currentData) 
    { 
        Ti.API.info(index + " exists: " + currentData[index]);
    }
    

    The accepted answer is wrong, it will give a false negative if the value at index is undefined:

    const currentData = ['a', undefined], index = 1;
    
    if (index in currentData) {
      console.info('exists');
    }
    // ...vs...
    if (typeof currentData[index] !== 'undefined') {
      console.info('exists');
    } else {
      console.info('does not exist'); // incorrect!
    }

    0 讨论(0)
  • 2020-12-07 10:34
    var demoArray = ['A','B','C','D'];
    var ArrayIndexValue = 2;
    if(ArrayIndexValue in demoArray){
       //Array index exists
    }else{
       //Array Index does not Exists
    }
    
    0 讨论(0)
  • 2020-12-07 10:36

    If you use underscore.js then these type of null and undefined check are hidden by the library.

    So your code will look like this -

    var currentData = new Array();
    
    if (_.isEmpty(currentData)) return false;
    
    Ti.API.info("is exists  " + currentData[index]);
    
    return true;
    

    It looks much more readable now.

    0 讨论(0)
  • 2020-12-07 10:37

    This way is easiest one in my opinion.

    var nameList = new Array('item1','item2','item3','item4');
    
    // Using for loop to loop through each item to check if item exist.
    
    for (var i = 0; i < nameList.length; i++) {
    if (nameList[i] === 'item1') 
    {   
       alert('Value exist');
    }else{
       alert('Value doesn\'t exist');
    }
    

    And Maybe Another way to do it is.

    nameList.forEach(function(ItemList)
     {
       if(ItemList.name == 'item1')
            {
              alert('Item Exist');
            }
     }
    
    0 讨论(0)
  • 2020-12-07 10:37

    This also works fine, testing by type against undefined.

    if (currentData[index] === undefined){return}
    

    Test:

    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    
    if (fruits["Raspberry"] === undefined){
      console.log("No Raspberry entry in fruits!")
    }

    0 讨论(0)
  • 2020-12-07 10:40

    Consider the array a:

    var a ={'name1':1, 'name2':2}
    

    If you want to check if 'name1' exists in a, simply test it with in:

    if('name1' in a){
    console.log('name1 exists in a')
    }else
    console.log('name1 is not in a')
    
    0 讨论(0)
提交回复
热议问题