语法 类和对象 字符串 数组 日期和时间 数学 方法 元编程 jQuery Ajax 正则表达式 网络 设计模式 数据库 测试

发布于 2016-05-29 08:24:02 | 81 次阅读 | 评论: 0 | 来源: 网络整理

问题

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

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' )
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务