1

以下代码取自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);
    }
}
4

5 回答 5

3
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 ){...}
于 2012-08-05T16:59:52.487 回答
2

一些布尔数学:

!(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) {…}
于 2012-08-05T17:15:31.003 回答
0

我建议将语句封装成一个具有描述性名称的函数(我不明白你想做什么),然后调用

if (true == meaningfulConditionName(list, callback))
{
    list.splice(i, 2);
}
于 2012-08-05T17:01:17.323 回答
0

不能比这更简化:

for (i = list.length - 2; i >= 0; i -= 2) callback && list[i] !== callback || context && list[i + 1] !== context || list.splice(i, 2)
于 2012-11-09T00:06:04.827 回答
-1

这是我的版本,通过了所有 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 );
  }                          
于 2012-08-05T17:31:09.513 回答