我有一段难看的Javascript代码
for (var k = 0; k < ogmap.length; ++k)
{
if (ogmap[k]["orgname"] == curSelectedOrg)
{
ogmap[k]["catnames"].push(newCatName);
break;
}
}
实际上,我的Web应用程序中有很多类似的内容。
我想知道是否有办法使它更漂亮,更紧凑。我知道有其他语言可以执行此操作的好方法,例如在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);
}