Convert Object to Number.png
1.Object
[JavaScript]
/*** object.valueOf() 返回对象本身 ***/
var obj = {x: 1, y: 2};
obj.valueOf(); //=> {x: 1, y: 2}
obj = {};
obj.valueOf(); //=> {}
2.Array
[JavaScript]
/*** Array.valueOf() 返回对象本身 ***/
var arr = [1, 2, 3];
arr.valueOf(); //=> [1, 2, 3]
arr = [1];
arr.valueOf(); //=> [1]
arr = [];
arr.valueOf(); //=> []
3.Function
[JavaScript]
/*** Function.valueOf() 返回对象本身 ***/
var func = function (x) { return x + 1 };
func.valueOf(); //=> ƒ (x) { return x + 1 }
4.Date
[JavaScript]
/*** Date.valueOf(),返回1970.1.1以来的毫秒数 ***/
var dt = new Date();
dt.valueOf(); //=> 1523702519206
5.RegExp
[JavaScript]
/*** RegExp.valueOf() 返回对象本身 ***/
var reg = /\d+/g;
reg.valueOf(); //=> /\d+/g
实例1
[JavaScript]
//对象obj转换为Number类型
var obj = {x: 1, y: 2};
obj.valueof(); //=> {x: 1, y: 2},非原始值
obj.toString(); //=> "[object Object]",原始值
"[object Object]" => NaN
实例2
[JavaScript]
//数组arrj转换为Number类型
var arr = [1, 2, 3];
arr.valueOf(); //=> [1, 2, 3],非原始值
arr.toString(); //=> "1,2,3",原始值
"1,2,3" => NaN
-------------------------------
arr = [9];
arr.valueOf(); //=> [9],非原始值
arr.toString(); //=> "9",原始值
"9" => 9
-------------------------------
arr = [];
arr.valueOf(); //=> [],非原始值
arr.toString(); //=> "",原始值
"" => 0
实例3
[JavaScript]
//函数func转换为Number类型
var func = function (x) { return x + 1 };
func.valueOf(); //=> ƒ (x) { return x + 1 },非原始值
func.toString(); //=> "function (x) { return x + 1 }",原始值
"function (x) { return x + 1 }" => NaN