函数 valueOf()
该函数用于返回指定对象的原始值。不同对象返回结果值如下
| 对象 | 返回值 |
|---|---|
| Array | 数组对象本身。 |
| Boolean | 布尔值。 |
| Date | 以毫秒数存储的时间值,从 UTC 1970 年 1 月 1 日午夜开始计算。 |
| Function | 函数本身。 |
| Number | 数字值。 |
| Object | 对象本身。这是默认设置。 |
| String | 字符串值。 |
// Array 返回数组对象本身
let array = ['a', 'b']
console.log(array.valueOf()) // ['a', 'b']
// Date 返回当前时间距1970年1月1日午夜的毫秒数
let date = new Date(2021, 9, 18, 23, 11, 59, 230)
console.log(date.valueOf()) // number 1634569919230
/*+---- Number 返回数字值 ----+*/
let num = 15
console.log(num.valueOf()) // number 15
let newNum = new Number(16)
console.log(newNum.valueOf()) // number 16
/*+---- Boolean 返回布尔值true或false ----+*/
let bool = true;
console.log(bool.valueOf()); // boolean true
var newBool = new Boolean(true)
console.log(newBool.valueOf()) // boolean true
// newBool.valueOf()返回的类型是boolean,newBool原本是object,因此返回false
console.log(newBool.valueOf() === newBool) // false
/*+---- Function 返回函数本身 ----+*/
function foo(){}
console.log( foo.valueOf() ); // function f
var foo2 = new Function("x", "y", "return x + y;");
console.log( foo2.valueOf() ); // function f
// 这里返回的类型都市funtion,因此调用了typeof相等
console.log( typeof foo2 === typeof foo )
/*+---- Object 返回对象本身 ----+*/
var obj = { name: "张三", age: 18 };
console.log( obj.valueOf() ); // object { name: "张三", age: 18 }
/*+---- String 返回字符串值 ----+*/
var str = "a";
console.log( str.valueOf() ); // string a
// new一个字符串对象
var str2 = new String("a");
// str2.valueOf()返回的类型是string,str2原本是object,因此返回false
console.log( str2.valueOf() === str2 ); // false
