我有一段丑陋的 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/