以下代码取自Backbone.js Events#off()
如何简化 IF 部分使其易于理解?
for (i = list.length - 2; i >= 0; i -= 2) {
if (!(callback && list[i] !== callback || context && list[i + 1] !== context)) {
list.splice(i, 2);
}
}
以下代码取自Backbone.js Events#off()
如何简化 IF 部分使其易于理解?
for (i = list.length - 2; i >= 0; i -= 2) {
if (!(callback && list[i] !== callback || context && list[i + 1] !== context)) {
list.splice(i, 2);
}
}
var noCallback = callback && list[i] !== callback;
var noContext = context && list[i + 1] !== context;
if(! noCallback && ! noContext){...}
或者按照评论中的建议删除否定:
var callbackCheck = !callback || list[i] === callback;
var contextCheck = !context || list[i + 1] === context;
if(callbackCheck && contextCheck ){...}
一些布尔数学:
!(callback && list[i] !== callback || context && list[i + 1] !== context)
!(!(!callback || list[i] === callback) || !(!context || list[i + 1] === context))
(!callback || list[i] === callback) && (!context || list[i + 1] === context)
为了使单个部分更容易理解,请使用说出变量名(我不知道这个范围,你可能会找到更好的东西):
var rightCallback = !callback || list[i] === callback;
var rightContext = !context || list[i + 1] === context;
if (rightCallback && rightContext) {…}
我建议将语句封装成一个具有描述性名称的函数(我不明白你想做什么),然后调用
if (true == meaningfulConditionName(list, callback))
{
list.splice(i, 2);
}
不能比这更简化:
for (i = list.length - 2; i >= 0; i -= 2) callback && list[i] !== callback || context && list[i + 1] !== context || list.splice(i, 2)
这是我的版本,通过了所有 Backbone.js 测试,并且会比原来的版本慢
if(
// callback defined, context is null
// remove callback for all context
( callback && list[i] === callback
&& !context)
// callback defined and context is defined
// ie remove specified callback for specified context
|| ( callback && list[i] === callback
&& context && list[i+1] === context)
// callback NOT defined and context is defined
// ie removed all callback for specific context
|| ( !callback && list[i] !== callback
&& context && list[i+1] === context )
// callback NOT defined and context NOT defined
// i.e. removed everything, this is unreachable code
// as it is caught by
// https://github.com/documentcloud/backbone/blob/master/backbone.js#L112
// and https://github.com/documentcloud/backbone/blob/master/backbone.js#L103
|| ( !callback && !context )
) {
// remove callback and context
list.splice( i, 2 );
}