Today, I was wandering around on the Net and accidentally saw a question: how much is a number multiplied by a date? I was surprised to see it in my heart, and I was blindsided by this kind of ghost question. So he did some research.
3 * new Date(a)/ / 4692361990902
Copy the code
It looks like it’s 3 times the timestamp. How to obtain the timestamp of Date? We know it is
new Date().valueOf() / / 1564120663634
Copy the code
Is it multiplied by valueOf()? The valueOf function is defined in the Object prototype.
Object.prototype.valueOf ƒ valueOf() {[native code]}
Copy the code
3 times an object, all times its valueOf valueOf(). Give it a try!
function Test(value) {
this.value = value;
}
Test.prototype.valueOf = function() {
return this.value;
}
const test = new Test(3);
3 * test; / / 9
Copy the code
That’s true!
So let’s see what the default valueOf is.
function Test(value) {
this.value = value;
}
const test = new Test(3);
test.valueOf(); // Test {value: 3}
3 * test; // NaN
Copy the code
The object itself is returned. So 3 times this is NaN. Common built-in object valueOf values:
Number(3).valueOf(); / / 3
String("3").valueOf(); / / "3"
[1.2.3].valueOf(); / / [1, 2, 3]
Boolean(3).valueOf(); // true
(function(){}).valueOf(); / / ƒ () {}
({a:3}).valueOf(); // {a: 3}.Copy the code
As you can roughly conclude from the above results, if valueOf is not defined, then the return value is the object itself. Look again at the documentation for valueOf. link
JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
ValueOf is used to return the original valueOf an object. No wonder a number multiplied by an object is multiplied by its valueOf value. So what happens when a number is multiplied by several primitive types of data?
3 * null; / / 0
3 * undefined; // NaN
3 * "s"; // NaN
3 * "3"; / / 9
3 * true; / / 3
3 * false; / / 0
3 * 3; / / 9
3 * NaN; // NaN
3 * {}; // NaN
3 * [3]; / / 9
3 * Symbol(3); // Uncaught TypeError: Cannot convert a Symbol value to a number
Copy the code
It turns out that when a number is multiplied by a primitive type, other data is cast. What happens if I reverse the order of multiplication?
{} * 3; // Uncaught SyntaxError: Unexpected token *
Copy the code
All the other results are the same, except for this one.
* ({})3; // NaN
Copy the code
{} are JavaScript braces, sorry to disturb ~~
To sum up. It’s a number multiplied by an object, multiplied by valueOf() of the object. When basic types are multiplied, they are converted and multiplied.