您当前的位置: 首页 > 

@大迁世界

暂无认证

  • 2浏览

    0关注

    739博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

在 JS 中检查变量是否为数组的多种方式,并说说 ES6 引入检查数组的缘起!

@大迁世界 发布时间:2020-08-19 07:53:07 ,浏览量:2

作者:Samantha Ming 译者:前端小智 来源:medium

点赞再看,微信搜索 【大迁世界】 关注这个没有大厂背景,但有着一股向上积极心态人。本文 GitHub https://github.com/qq449245884/xiaozhi 上已经收录,文章的已分类,也整理了很多我的文档,和教程资料。

下面的代码片段用于检查变量或值是否为数组。 在主流的浏览器可以使用Array.isArray方法。 对于较旧的浏览器,可以使用polyfill👍

const variable = ['🍝', '🍜', '🍲'];

// 主流浏览器
Array.isArray(variable);

// 老式浏览器
Object.prototype.toString.call(variable) === '[object Array]';
检查数组的现代方法

检查数组的最佳方法是使用内置的Array.isArray()👏

Array.isArray([]); // true
Array.isArray(['🍝']); // true
Array.isArray(new Array('🍝')); // true
浏览器支持

浏览器对 Array.isArray()的支持非常好 👍

在这里插入图片描述

适用于旧版浏览器的 Polyfill

如果需要让较早的浏览器支持,则可以使用此MDN polyfill。

if (!Array.isArray) {
  Array.isArray = function(org) {
    return Object.prototype.toString.call(org) === '[object Array]'
  }
}
其它方式:使用 Lodash 或 Underscore

如果你使用的是外部库,它们也有一些内置方法👏

Lodash

检查值是否为数组对象。

const array = ['🍝', '🍜', '🍲'];
const notArray = 'not array';

_.isArray(array); // true
_.isArray(notArray); // false
Underscore

如果对象是数组,返回 true。

const array = ['🍝', '🍜', '🍲'];
const notArray = 'not array';

_.isArray(array); // true
_.isArray(notArray); // false
为什么我们不能使用typeof?

通常,我们要检查值的类型,我们只需使用 typeof

typeof 'string'; // 'string'
typeof 100; // 'number'
typeof true; // 'boolean'
typeof false; // 'boolean'
typeof function() {}; // 'function'
typeof {}; // 'object'

typeof []; // 'object'             
关注
打赏
1664287990
查看更多评论
0.0383s