TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Beautiful Code: Is there a better way of writing v = (v == 0? 1 : 0);

21 点作者 hydrazine将近 14 年前

6 条评论

Cushman将近 14 年前
Summary: No.<p>Long version: There are a number of ways which are lexically shorter, do the same thing only assuming that v is already either 0 or 1, are not self-documenting, and perform worse or marginally better at best. Only a very tortured definition would call any of these things "better".<p>Although v = v ? 0 : 1 isn't that bad.
评论 #2890347 未加载
gte910h将近 14 年前
If you insist on one line<p><pre><code> if (v&#62;0) v=0; else v=1; </code></pre> Otherwise<p><pre><code> if(v&#62;0) v=0; else v=1; </code></pre> Some of us prize readability over neat tricks. I think there are a 100 ways most of these answers could be misinterpreted by people. Code is read more than it is written, and programs rarely work better because you wrote it slightly more "impressively". Modern compilers do much of this sort of stuff that they are doing in this thread, but they do it in a repeatable manner which future programmers don't have to puzzle out.
codeslush将近 14 年前
v = !v - if toggling between true | false
michaelcampbell将近 14 年前
Are you just toggling between 1 and 0?<p>Why not v = 1 - v?
wycats将近 14 年前
v ^= 1 in Ruby should work.
DrJ将近 14 年前
v = v || 1;