CoffeeScript 检查变量的类型是否为数组

检查变量的类型是否为数组

问题

你希望检查一个变量是否为一个数组。

myArray = []
console.log typeof myArray // outputs object

“typeof”运算符为数组输出了一个错误的结果。

解决方案

使用下面的代码:

typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is [object Array]

为了使用这个,像下面这样调用typeIsArray就可以了。

myArray = []
typeIsArray myArray // outputs true

讨论

上面方法取自”the Miller Device”。另外一个方式是使用Douglas Crockford的片段。

typeIsArray = ( value ) ->
    value and
        typeof value is object and
        value instanceof Array and
        typeof value.length is number and
        typeof value.splice is function and
        not ( value.propertyIsEnumerable length )

作者:唐伯虎点蚊香,如若转载,请注明出处:https://www.web176.com/coffeescript/10678.html

(0)
打赏 支付宝 支付宝 微信 微信
唐伯虎点蚊香的头像唐伯虎点蚊香
上一篇 2023年2月26日
下一篇 2023年2月26日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注