JavaScript中的'+ new'是什么意思?

时间:2021-09-07 21:17:42

Looking through the jQuery source in the function now() I see the following:

通过函数now()查看jQuery源代码,我看到以下内容:

function now(){
    return +new Date;
}

I've never seen the plus operator prepended to the new operator like this. What does it do?

我从来没有见过像这样的新运算符前置加号运算符。它有什么作用?

3 个解决方案

#1


27  

Nicolás and Brian are right, but if you're curious about how it works, +new Date(); is equivalent to (new Date()).valueOf();, because the unary + operator gets the value of its operand expression, and then converts it ToNumber.

Nicolás和Brian是对的,但是如果你对它的工作原理感到好奇,那么+ new Date();等价于(new Date())。valueOf();,因为一元+运算符获取其操作数表达式的值,然后将其转换为ToNumber。

You could add a valueOf method on any object and use the unary + operator to return a numeric representation of your object, e.g.:

您可以在任何对象上添加valueOf方法,并使用一元+运算符返回对象的数字表示,例如:

var productX = {
  valueOf : function () {
    return 500; // some "meaningful" number
  }
};

var cost = +productX; // 500

#2


10  

I think the unary plus operator applied to anything would cause it to be converted into a number.

我认为应用于任何事物的一元加运算符会导致它被转换为数字。

#3


9  

It converts the Date() into an integer, giving you the current number of milliseconds since January 1, 1970.

它将Date()转换为整数,为您提供自1970年1月1日以来的当前毫秒数。

#1


27  

Nicolás and Brian are right, but if you're curious about how it works, +new Date(); is equivalent to (new Date()).valueOf();, because the unary + operator gets the value of its operand expression, and then converts it ToNumber.

Nicolás和Brian是对的,但是如果你对它的工作原理感到好奇,那么+ new Date();等价于(new Date())。valueOf();,因为一元+运算符获取其操作数表达式的值,然后将其转换为ToNumber。

You could add a valueOf method on any object and use the unary + operator to return a numeric representation of your object, e.g.:

您可以在任何对象上添加valueOf方法,并使用一元+运算符返回对象的数字表示,例如:

var productX = {
  valueOf : function () {
    return 500; // some "meaningful" number
  }
};

var cost = +productX; // 500

#2


10  

I think the unary plus operator applied to anything would cause it to be converted into a number.

我认为应用于任何事物的一元加运算符会导致它被转换为数字。

#3


9  

It converts the Date() into an integer, giving you the current number of milliseconds since January 1, 1970.

它将Date()转换为整数,为您提供自1970年1月1日以来的当前毫秒数。