簡體   English   中英

在Javascript中,是否有一個“如果...發現”的等效項,或者是一種緊湊的方式來執行我想做的事情?

[英]In Javascript, is there an equivalent of a “find if”, or a compact way of doing what I'm trying to do?

我有一段難看的Javascript代碼

for (var k = 0; k < ogmap.length; ++k)
{
    if (ogmap[k]["orgname"] == curSelectedOrg)
    {
        ogmap[k]["catnames"].push(newCatName);
        break;
    }
} 

實際上,我的Web應用程序中有很多類似的內容。

我想知道是否有辦法使它更漂亮,更緊湊。 我知道有其他語言這樣做的很好的途徑,如使用find_if在C ++( http://www.cplusplus.com/reference/algorithm/find_if/ )或FirstOrDefault在C#或花哨LINQ查詢在C#。

至少,請幫助我使它更具可讀性。

我想說的是,您可以編寫一個實用程序函數,然后在必要時使用它。

// finds the first object in the array that has the desired property
// with a value that matches the passed in val
// returns the index in the array of the match
// or returns -1 if no match found
function findPropMatch(array, propName, val) {
   var item;
   for (var i = 0; i < array.length; i++) {
       item = array[i];
       if (typeof item === "object" && item[propName] === val) {
           return i;
       }
   }
   return -1;
}

然后,您可以像這樣使用它:

var match = findPropMatch(ogmap, "orgname", curSelectedOrg);
if (match !== -1) {
    ogmap[match]["catnames"].push(newCatName);
}
var find_if = function (arr, pred) {
    var i = -1;
    arr.some(function (item, ind) {
        if (pred(item)) {
            i = ind;
            return true;
        }
    });
    return i;
}

像這樣稱呼它

var item_or_last = find_if(_.range(ogmap.length), function (item) {
    return item["orgname"] == curSelectedOrg
});

還是沒有underscore.js

var range = function (a, b) {
    var low = a < b ? a : b;
    var high = a > b ? a : b;
    var ret = [];
    while (low < high) {
        ret.push(low++);
    }
    return ret;  
}
var item_or_last = find_if(range(0, ogmap.length), function (item) {
    return item["orgname"] == curSelectedOrg
});

這使您可以聲明要查找的內容,而不必遍歷項目並檢查每一項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM