gpt4 book ai didi

javascript - + Javascript 中的运算符

转载 作者:搜寻专家 更新时间:2023-11-01 05:11:17 25 4
gpt4 key购买 nike

所以我注意到

的结果
(new Date())

是一个日期对象;在这种情况下

Date {Thu Dec 04 2014 22:43:07 GMT+0200 (SAST)}

但是如果我输入

+(new Date())

我得到一个整数值;

1417725787989

这是怎么做到的?

我有一个名为“Duration”的函数,当它像这样使用时:

new Duration(352510921)

返回一个看起来像这样的实例:

{ days:5, hours:3, mins:55, secs:10, ms:921 }    

那么如何使用 + 运算符获取 Duration 实例的 int 值呢?

var dur = new Duration(352510921);
console.log(+dur) // prints int value 352510921

最佳答案

一元 + 运算符将实例转换为 Number,就像调用 Number() 函数将变量转换为一个数字

如果您想覆盖特定实例的转换方式,您需要覆盖该实例的 valueOf 属性:

var a = {
valueOf: function () {
return 5;
}
};
console.log(a); //Object { valueOf: function () {...} }
console.log(+a); //5

来自ES5 standard :

11.4.6 Unary + Operator # Ⓣ Ⓡ Ⓖ

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Return ToNumber(GetValue(expr)).
对象上的

ToNumber 将导致 ToPrimitive与提示号码。 ToPrimitive 将调用 [[DefaultValue]]内部方法指出:

When the [[DefaultValue]] internal method of O is called with hint Number, the following steps are taken:

  1. Let valueOf be the result of calling the [[Get]] internal method of object O with argument "valueOf".
  2. If IsCallable(valueOf) is true then,
    1. Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.
    2. If val is a primitive value, return val.
  3. Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
  4. If IsCallable(toString) is true then,
    1. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
    2. If str is a primitive value, return str.
  5. Throw a TypeError exception.

关于javascript - + Javascript 中的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27303803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com