search for element within an array

前端 未结 3 1380

My data[l][m] contains 1,2,3,4,5 I\'m trying to search for a particular number, say \'2\' in it. Is there a better way to do this?

for          


        
相关标签:
3条回答
  • 2021-01-29 01:10

    You could use indexOf, although it still has the same O(n) complexity as your for loop:

    var pos = data[l][m].indexOf(num);
    if (pos !== -1)
    {
      // element was found
      number = data[l][0];
      document.form.options[l-1] = new Option(number,number,true,true);
    }
    

    Note, however, that older versions of IE do not have the indexOf method for Arrays.

    0 讨论(0)
  • 2021-01-29 01:13

    If you're already including jQuery, use $.inArray(), like this:

    if($.inArray(num, data[l][m]) > -1) {
      number = data[l][0];
      document.form.options[l-1] = new Option(number,number,true,true);
    }
    

    The shorter vanilla JS version is a direct .indexOf() on the Array, but IE doesn't have this by default.

    0 讨论(0)
  • 2021-01-29 01:27

    I have no major changes to recommend, but do have a couple tweaks to suggest. The first is to create a temporary reference to data[l] to reduce reading complexity by 1 level. This is a cosmetic change for the benefit of the coder. The other is cache the length of the array you are searching, which helps with performance. If you replace your for loop with the while loop as follows, you can also remove the comparison operations.

    var layer1 = data[l];
    var n = layer1[m].length;
    while (n--) {
        if (layer1[m][n] == num) { // num is equal to '2' 
            number = layer1[0];
            document.form.options[l - 1] = new Option(number, number, true, true);
        }
    }
    
    0 讨论(0)
提交回复
热议问题