Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

关于按位非操作符(~)的问题?

$
0
0

今天在看vue-hackernews的源代码,发现这样一段代码:

export function fromNow (time) {
  const between = Date.now() / 1000 - Number(time)
  if (between < 3600) {
    return pluralize(~~(between / 60), ' minute')
  } else if (between < 86400) {
    return pluralize(~~(between / 3600), ' hour')
  } else {
    return pluralize(~~(between / 86400), ' day')
  }
}

function pluralize(time, label) {
    if (time === 1) {
        return time + label
    }
    return time + label + 's';
}

其中~~(between / 60),不明白为什么要这样写?

对任一数值 x 进行按位非操作的结果为 -(x + 1),那~~x的结果是-(-(x+1)+1),结果还是x,那为什么还要在前面加上~~呢?


Viewing all articles
Browse latest Browse all 14821

Trending Articles