最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple operations in ternary operator - Stack Overflow

programmeradmin7浏览0评论

Is it possible to have multiple operations within a ternary operator's if/else?

I've e up with an example below, probably not the best example but I hope you get what I mean.

var totalCount = 0;
var oddCount = 0;
var evenCount = 0;
for(var i = 0; i < arr.length; i++) {
  if(arr[i] % 2 === 0) {
    evenCount ++;
    totalCount ++;
  } else {
    oddCount ++;
    totalCount ++;
  }
}

into something like:

var totalCount = 0;
var oddCount = 0;
var evenCount = 0;
for(var i = 0; i < arr.length; i++) {
  arr[i] % 2 === 0? evenCount ++ totalCount ++ : oddCount ++ totalCount ++;
  }
}

Is it possible to have multiple operations within a ternary operator's if/else?

I've e up with an example below, probably not the best example but I hope you get what I mean.

var totalCount = 0;
var oddCount = 0;
var evenCount = 0;
for(var i = 0; i < arr.length; i++) {
  if(arr[i] % 2 === 0) {
    evenCount ++;
    totalCount ++;
  } else {
    oddCount ++;
    totalCount ++;
  }
}

into something like:

var totalCount = 0;
var oddCount = 0;
var evenCount = 0;
for(var i = 0; i < arr.length; i++) {
  arr[i] % 2 === 0? evenCount ++ totalCount ++ : oddCount ++ totalCount ++;
  }
}
Share Improve this question asked Oct 26, 2016 at 15:49 WillKreWillKre 6,1586 gold badges35 silver badges64 bronze badges 2
  • stackoverflow./questions/6678411/… – Mahi Commented Oct 26, 2016 at 15:51
  • 3 If you need to confuse other programmers, this is the way to go. – user1023602 Commented Oct 26, 2016 at 15:53
Add a ment  | 

1 Answer 1

Reset to default 17

You can use the ma operator to execute multiple expressions in place of a single expression:

arr[i] % 2 === 0? (evenCount++, totalCount++) : (oddCount++, totalCount++);

The result of the ma operator is the result of the last expression.

But yeah, don't use the conditional operator for side effects.

发布评论

评论列表(0)

  1. 暂无评论