valueOf method
时间: 2023-10-01 18:02:07 浏览: 45
The `valueOf()` method in JavaScript is a built-in method that converts a primitive data type (such as a string or a number) into a corresponding object wrapper of that primitive type.
For example, if we have a string value "123", we can use the `valueOf()` method to convert it into a number value 123:
```
let str = "123";
let num = Number(str.valueOf()); // num = 123
```
Similarly, we can use the `valueOf()` method to convert a number value into a string value:
```
let num = 123;
let str = num.valueOf().toString(); // str = "123"
```
Note that the `valueOf()` method is automatically called by JavaScript when an object is used in a context where a primitive value is expected. For example, if we try to concatenate a string and an object, the `valueOf()` method will be called on the object to convert it into a string:
```
let obj = { value: 123 };
let str = "The value is " + obj; // str = "The value is [object Object]"
```
In this case, the `valueOf()` method of the object returns the primitive value of the object, which is then concatenated with the string.