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

前端 未结 18 1688
粉色の甜心
粉色の甜心 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:42
    const arr = []
    
    typeof arr[0] // "undefined"
    
    arr[0] // undefined
    

    If boolean expression

    typeof arr[0] !== typeof undefined
    

    is true then 0 is contained in arr

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

    If you are looking for some thing like this.

    Here is the following snippetr

    var demoArray = ['A','B','C','D'];
    var ArrayIndexValue = 2;
    if(demoArray.includes(ArrayIndexValue)){
    alert("value exists");
       //Array index exists
    }else{
    alert("does not exist");
       //Array Index does not Exists
    }

    0 讨论(0)
  • 2020-12-07 10:46
    var myArray = ["Banana", "Orange", "Apple", "Mango"];
    
    if (myArray.indexOf(searchTerm) === -1) {
      console.log("element doesn't exist");
    }
    else {
      console.log("element found");
    }
    
    0 讨论(0)
  • 2020-12-07 10:46

    When trying to find out if an array index exists in JS, the easiest and shortest way to do it is through double negation.

    let a = [];
    a[1] = 'foo';
    console.log(!!a[0])   // false
    console.log(!!a[1])   // true
    
    0 讨论(0)
  • 2020-12-07 10:47

    Someone please correct me if i'm wrong, but AFAIK the following is true:

    1. Arrays are really just Objects under the hood of JS
    2. Thus, they have the prototype method hasOwnProperty "inherited" from Object
    3. in my testing, hasOwnProperty can check if anything exists at an array index.

    So, as long as the above is true, you can simply:

    const arrayHasIndex = (array, index) => Array.isArray(array) && array.hasOwnProperty(index);

    usage:

    arrayHasIndex([1,2,3,4],4); outputs: false

    arrayHasIndex([1,2,3,4],2); outputs: true

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

    I had to wrap techfoobar's answer in a try..catch block, like so:

    try {
      if(typeof arrayName[index] == 'undefined') {
        // does not exist
      }
      else {
      // does exist
      }
    } 
    catch (error){ /* ignore */ }
    

    ...that's how it worked in chrome, anyway (otherwise, the code stopped with an error).

    0 讨论(0)
提交回复
热议问题