我必须写很多
for ( var prop in obj )
{
if ( condition(prop) )
{
// ...
}
}
在我的生产代码中键入部分。以下是一些直接复制粘贴的示例。
(1)
for ( var region in this.DealsByRegion ) // iterate through regions
{
if ( this.RegionsChecked[region] === true ) // if region is checked in table
{
num_deal_opportunities += region.NumOpportunities;
total_deal_percentage += region[dealName] * region.NumOpportunities;
}
}
(2)
for ( var deal_name in this.DealsChecked )
{
if ( this.DealsChecked[deal_name] === true )
{
offer_data.push({ value: deal_percentages[deal_name],
color: this.ColorStack[(this.ColorStack.length + i) % this.ColorStack],
highlight: this.HighlightColor,
label: deal_name });
}
}
当然还有很多情况
for ( var thisguy in theseguys )
{
if (theseguys.hasOwnProperty(thisguy)
{
// ...
}
}
我想知道是否有办法使它更加优雅和紧凑。我尝试编写类似LINQ的Where子句
// helper function for iterating through a filtered set of properties
Object.prototype.PropsWhere = function ( cond )
{
var propsWhere = [];
for ( var prop in this )
{
if ( cond(prop) )
{
propsWhere.push(prop);
}
}
return propsWhere;
}
但是当我尝试使用它时,我意识到它实际上使所有内容都变得不那么紧凑和易读,因此我不得不处理一个新的this
yada-yada。
我应该如何应对这些情况?
如果发现必须编写许多遍历对象属性的条件语句,则可能需要重新检查模式。
使用您的地区示例:
for ( var region in RegionsChecked ) // iterate through checked regions
{
num_deal_opportunities += region.NumOpportunities;
total_deal_percentage += region[dealName] * region.NumOpportunities;
}
这样,您的容器仅包含对您关心的对象的引用-而不是创建“元容器”来告诉您您关心的对象的ID。
不确定这对于您的基础结构是否可行-但要查看是否可以创建所需对象的容器-而不是告诉其他容器中需要哪些对象的中间容器。
另一种方法是使用“已检查”属性/字段标记对象本身。但是,我的猜测是,您不希望通过瞬时性的方式污染对象,例如是否当前对其进行检查。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句