search for element within an array

前端 未结 3 1388

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: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);
        }
    }
    

提交回复
热议问题