javascript - 在Javascript中,是否有相当于 "find if"的东西,或者是一种紧凑的方式来完成我想做的事情?

标签 javascript c++ algorithm

我有一段丑陋的 Javascript 代码

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

实际上,我的网络应用程序中有很多类似的部分。

我想知道是否有办法让它更漂亮、更紧凑。我知道在其他语言中也有很好的方法,例如在 C++ 中使用 find_if ( http://www.cplusplus.com/reference/algorithm/find_if/ ) 或在 C# 中使用 FirstOrDefault 或在 C# 中使用奇特的 LINQ 查询。

至少,帮助我使其更具可读性。

最佳答案

我想说,您可以自己编写一个实用函数,然后在需要时使用它。

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

关于javascript - 在Javascript中,是否有相当于 "find if"的东西,或者是一种紧凑的方式来完成我想做的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30386082/

相关文章:

javascript - 假设我有这个 javascript 函数。我如何将元素传递给它?

python - 给定一个 Python 列表列表,找到所有可能的保持每个子列表顺序的平面列表?

php - 查找字符串数组的公共(public)前缀

javascript - angularJS:单元测试给出:未知提供者:$httpProviderProvider <- $httpProvider

javascript - 如何在 Three.js 中淡入/淡出背景?

javascript - tablesorter header 设置为 sort false,但仍然排序

c++ - 从 vector 中排序和提取元素

c++ - 在 C++ 中格式化带小数秒的日期和时间

c++ - std :sort with & parametr c++ 的排序函数

python - 算法问题,python字符串,不知道