Checking if element exists in array without iterating through it

my array:

tempListArray = "[{"id":"12","value":false},{"id":"10","value":false},{"id":"9","value":false},{"id":"8","value":false}]";

To check if an element exists I would do this:

for (var i in tempListArray) {
    //check flag
    if (tempListArray[i].id == Id) {
        flagExistsLoop = 1;
        break;
    }
} 

Is there anyway, I can check if an Id exists without looping through the whole array. Basically I am worried about performance if say I have a 100 elements.

Thanks


No, without using custom dictionary objects (which you seriously don't want to for this) there's no faster way than doing a 'full scan' of all contained objects.

As a general rule of thumb, don't worry about performance in any language or any situation until the total number of iterations hits 5 digits, most often 6 or 7. Scanning a table of 100 elements should be a few milliseconds at worst. Worrying about performance impact before you have noticed performance impact is one of the worst kinds of premature optimization.


No, you can't know that without iterating the array.

However, note for...in loops are a bad way of iterating arrays:

  • There is no warranty that it will iterate the array with order
  • It will also iterate (enumerable) non-numeric own properties
  • It will also iterate (enumerable) properties that come from the prototype, ie, defined in Array.prototype and Object.protoype .
  • I would use one of these:

  • for loop with a numeric index:

    for (var i=0; i<tempListArray.length; ++i) {
        if (tempListArray[i].id == Id) {
            flagExistsLoop = 1;
            break;
        }
    } 
    
  • Array.prototype.some (EcmaScript 5):

    var flagExistsLoop = tempListArray.some(function(item) {
        return item.id == Id;
    });
    

    Note it may be slower than the other ones because it calls a function at each step.

  • for...of loop (EcmaScript 6):

    for (var item of tempListArray) {
        if (item.id == Id) {
            flagExistsLoop = 1;
            break;
        }
    } 
    

  • 尝试使用php.js它可以帮助,而你可以使用相同的PHP函数名称,它有一些有用的功能

    链接地址: http://www.djcxy.com/p/25684.html

    上一篇: 评估数组是否有红宝石中的任何项目

    下一篇: 检查数组中是否存在元素而不迭代它