JSRUN 用代码说话

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

编辑教程

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

问题

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

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' )
JSRUN闪电教程系统是国内最先开创的教程维护系统, 所有工程师都可以参与共同维护的闪电教程,让知识的积累变得统一完整、自成体系。 大家可以一起参与进共编,让零散的知识点帮助更多的人。
X
支付宝
9.99
无法付款,请点击这里
金额: 0
备注:
转账时请填写正确的金额和备注信息,到账由人工处理,可能需要较长时间
如有疑问请联系QQ:565830900
正在生成二维码, 此过程可能需要15秒钟