Categories: CoffeeScript 教程

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 )
唐伯虎点蚊香

前端小白,想各位学习!

Share
Published by
唐伯虎点蚊香

Recent Posts

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 天 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

1 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

2 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

2 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

3 周 ago