想到的最佳解决方案是为此使用函数式方法。
let arr = [1,2,3,4,5,6,7,8,9]; // Huge array
let condFactory = (condition) => {
if (condition === 'one') {
console.log('This will only be called once, if condition==="one"',
'it will not be called for each element')
return (item, index) => console.log('one (called for each element)', item, index);
} else if (condition === 'two') {
console.log('This will only be called once, if condition==="two"',
'it will not be called for each element')
return (item, index) => console.log('two (called for each element)', item, index);
}
console.log('This will only be called once, if no condition matches',
'it will not be called for each element')
return (item, index) => console.log('No condition matched (called for each element)', item, index);
}
arr.forEach(condFactory(someOtherProperty));
对于 es5:
var arr = [1,2,3,4,5,6,7,8,9]; // Huge array
var condFactory = function(condition) {
if (condition === 'one') {
console.log('This will only be called once, if condition==="one"',
'it will not be called for each element')
return function(item, index) { console.log('one (called for each element)', item, index); };
} else if (condition === 'two') {
console.log('This will only be called once, if condition==="two"',
'it will not be called for each element')
return function(item, index) { console.log('two (called for each element)', item, index); };
}
console.log('This will only be called once, if no condition matches',
'it will not be called for each element')
return function(item, index) { console.log('No condition matched', item, index); };
}
arr.forEach(condFactory(someOtherProperty));
这样,用于每个条件的函数将在循环开始之前确定并用于循环内的每个元素。
你可以拉伸这个oneliner
arr.forEach(condFactory(someOtherProperty));
分成两行,看看为什么 if...else 只计算一次:
let functionBasedOnIfElse = condFactory(someOtherProperty); // Get the function based on your "someOtherProperty"
arr.forEach(functionBaseOnIfElse); // Pass reference to the function
如您所见,if...else 只会被评估一次。 if...else 返回的函数将被传递给 arr.forEach 并为数组中的每个元素调用。
编辑:添加默认返回。
Edit2:更正 es5 被剪断
Edit3:扩展案例以显示每个函数都应用于数组中的每个项目。
Edit4:添加更多关于为什么 if...else 只被评估一次的信息。
Edit5:添加几个console.log 以显示哪个部分将在哪个点被调用。