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

前端 未结 18 1686
粉色の甜心
粉色の甜心 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:23

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    if(fruits.indexOf("Banana") == -1){
        console.log('item not exist')
    } else {
    	console.log('item exist')
    }

    0 讨论(0)
  • 2020-12-07 10:25
    (typeof files[1] === undefined)?
                this.props.upload({file: files}):
                this.props.postMultipleUpload({file: files widgetIndex: 0, id})
    

    Check if the second item in the array is undefined using the typeof and checking for undefined

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

    Use typeof arrayName[index] === 'undefined'

    i.e.

    if(typeof arrayName[index] === 'undefined') {
        // does not exist
    }
    else {
        // does exist
    }
    
    0 讨论(0)
  • 2020-12-07 10:28

    you can simply use this:

    var tmp = ['a', 'b'];
    index = 3 ;
    if( tmp[index]){
        console.log(tmp[index] + '\n');
    }else{
        console.log(' does not exist');
    }
    
    0 讨论(0)
  • 2020-12-07 10:31

    If elements of array are also simple objects or arrays, you can use some function:

    // search object
    var element = { item:'book', title:'javasrcipt'};
    
    [{ item:'handbook', title:'c++'}, { item:'book', title:'javasrcipt'}].some(function(el){
        if( el.item === element.item && el.title === element.title ){
            return true; 
         } 
    });
    
    [['handbook', 'c++'], ['book', 'javasrcipt']].some(function(el){
        if(el[0] == element.item && el[1] == element.title){
            return true;
        }
    });
    
    0 讨论(0)
  • 2020-12-07 10:32

    Simple way to check item exist or not

    Array.prototype.contains = function(obj) {
        var i = this.length;
        while (i--)
           if (this[i] == obj)
           return true;
        return false;
    }
    
    var myArray= ["Banana", "Orange", "Apple", "Mango"];
    
    myArray.contains("Apple")
    
    0 讨论(0)
提交回复
热议问题