概率抽奖算法
/// <summary> /// 抽奖 /// </summary> /// <param name="probabilities">每个奖项的概率&
在业务系统中,写了一个方法并要求传入一个参数,参数必须为一个数组,但使用typeof
去检查的时候发现并不能获得想要的Array
字符。
var a = [1, 2, 3];
console.log(a); // Array[3]
console.log(typeof a); // "object"
结果表明,使用typeof
并不能得到原计划中的Array
。
typeof
可以检测基本类型包括 undefined
, string
, number
, boolean
,但是对于检测对象就不靠谱了。不只是Array
,javascript中的对象,包括 Date
, String
, Boolean
, Number
, Object
, Function
, Array
, RegExp
, Error
使用typof只会返回 "object"
。
使用 instanceof
或者 constructor
来检测 Array
也不是靠谱的办法。
ECMA中对Object.prototype.toString的解释:
When the toString method is called, the following steps are taken:
- Get the http://Class property of this object.
- Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
- Return Result (2)
其过程简单说来就是:1、获取对象的类名(对象类型)。2、然后将[object 类型]
组合并返回。
另外,使用Object.prototype.toString
,而不是Object.toString
是因为toString
可能被覆写。
var type=function(object){
return Object.prototype.toString.call(object);
}
type({}) //"[object Object]"
type([1,2,3,4]); //"[object Array]"
type(new Date()); //"[object Date]"
type(/^hello/); //"[object RegExp]"
type(new Error()) //"[object Error]"
type(new Number()) //"[object Number]"