在 JS 中檢查變量是否為數(shù)組的多種方式,并說說 ES6 引入檢查數(shù)組的緣起!
下面的代碼片段用于檢查變量或值是否為數(shù)組。在主流的瀏覽器可以使用Array.isArray方法。對(duì)于較舊的瀏覽器,可以使用polyfill
- const variable = ['🍝', '🍜', '🍲'];
- // 主流瀏覽器
- Array.isArray(variable);
- // 老式瀏覽器
- Object.prototype.toString.call(variable) === '[object Array]';
檢查數(shù)組的現(xiàn)代方法
檢查數(shù)組的最佳方法是使用內(nèi)置的Array.isArray()
- Array.isArray([]); // true
- Array.isArray(['🍝']); // true
- Array.isArray(new Array('🍝')); // true
瀏覽器支持
瀏覽器對(duì) Array.isArray()的支持非常好
適用于舊版瀏覽器的 Polyfill
如果需要讓較早的瀏覽器支持,則可以使用此MDN polyfill。
- if (!Array.isArray) {
- Array.isArray = function(org) {
- return Object.prototype.toString.call(org) === '[object Array]'
- }
- }
其它方式:使用 Lodash 或 Underscore
如果你使用的是外部庫,它們也有一些內(nèi)置方法??
Lodash
檢查值是否為數(shù)組對(duì)象。
- const array = ['🍝', '🍜', '🍲'];
- const notArray = 'not array';
- _.isArray(array); // true
- _.isArray(notArray); // false
Underscore
如果對(duì)象是數(shù)組,返回 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' <-- 😱
問題是數(shù)組實(shí)際上處于 Object 數(shù)據(jù)類型的保護(hù)傘之下。所以typeof 返回值是沒問題。不幸的是,這對(duì)我們并沒有什么幫助,因?yàn)槲覀冎幌霗z查值是不是數(shù)組。
typeof
Type | 例子 | 返回值 |
---|---|---|
String | typeof "hello" | "string" |
Boolean | typeof true typeof false |
"boolean" |
Number | typeof 100 | "number" |
Undefined | typeof undefined | "undefined" |
Function | typeof function() {} | "function" |
Null | typeof null | "object" |
非基本類型 | typeof {} typeof [] |
"object" |
基本類型
在 JS 中有 6 種基本數(shù)據(jù)類型
- string
- number
- bigint
- boolean
- undefined
- symbol
非基本類型 (對(duì)象)
對(duì)象是指包含數(shù)據(jù)和使用數(shù)據(jù)的指令的數(shù)據(jù)結(jié)構(gòu)。它們是通過引用存儲(chǔ)的
我比較喜歡稱它為“非基本類型 ”,但它們被稱為Object。
- object
- array
- function
盡管當(dāng)我們在函數(shù)上使用typeof來檢查函數(shù)的類型,它返回“ function”,但實(shí)際上它是一個(gè)對(duì)象。
》 MDN:盡管每個(gè) Function 構(gòu)造函數(shù)都是從 Object 構(gòu)造函數(shù)派生的,但它是Function的特殊簡寫形式。
代碼診斷
我收到了很多開發(fā)都提供用來檢查Array的不同解決方案。乍一看,它們似乎是不錯(cuò)的解決方案。有點(diǎn)遺憾的是,有些問題或極端情況使它們不理想。
Array.length 的問題
- const array = ['🍝', '🍜', '🍲'];
- array.length; // 3
如果數(shù)組有長度,我們可以假設(shè)它是數(shù)組?
遺憾的是,此解決方案的問題在于還有其他具有長度即即的數(shù)據(jù)類型,如:字符串。因此,這可能導(dǎo)致誤報(bào)。
- const string = 'not array';
- string.length; // 9
即使一個(gè)對(duì)象也可以有l(wèi)ength屬性:
- const object = { length: 2 };
- const array = ['🍝', '🍜', '🍲'];
- typeof array === 'object' && Boolean(array.length); // true
- typeof object === 'object' && Boolean(object.length); // true <-- 😱
instanceof 的問題
- const array = ['🍝', '🍜', '🍲'];
- array instanceof Array; // true
這種方法在 ES5 很常見, 在許多情況下,這種可以很好的工作。但是,這有一個(gè)陷阱!它不適用于多個(gè)上下文(例如 框架 或windows)。因?yàn)槊總€(gè)框架在其自己的執(zhí)行環(huán)境中都有不同的作用域。因此,它具有不同的全局對(duì)象和不同的構(gòu)造函數(shù)。因此,如果嘗試針對(duì)該框架的上下文測試數(shù)組,則該數(shù)組不會(huì)返回true,而會(huì)錯(cuò)誤地返回false。
window.frames: frames[] 是窗口中所有命名的框架組成的數(shù)組。這個(gè)數(shù)組的每個(gè)元素都是一個(gè)Window對(duì)象,對(duì)應(yīng)于窗口中的一個(gè)框架。
- const frameNode = document.createElement('iframe'); // 創(chuàng)建一個(gè)iframe元素節(jié)點(diǎn)
- document.body.appendChild(frameNode);
- // 從我們當(dāng)前的窗口訪問框架
- const frameBrowser = window.frames[window.frames.length - 1];
- // 訪問我們創(chuàng)建的框架的“數(shù)組”對(duì)象
- frameArray = frameBrowser.Array;
- // 在我們的框架環(huán)境中創(chuàng)建一個(gè)新的數(shù)組
- const newFrameArray = new frameArray('🍝', '🍜', '🍲');
- newFrameArray instanceof Array; // ❌ false
- Array.isArray(newFrameArray); // ✅ true
構(gòu)造函數(shù)的問題
- const array = ['🍝', '🍜', '🍲'];
- array.constructor === Array; // true
這是另一個(gè)很好的解決方案。不幸的是,這和instanceof有同樣的問題。它也不能在多個(gè)上下文中工作。
- // ...
- newFrameArray.constructor === Array; // ❌ false
- Array.isArray(newFrameArray); // ✅ true
作者:Samantha Ming 譯者:前端小智 來源:medium
原文:https://www.samanthaming.com/tidbits/89-how-to-check-if-variable-is-array/
本文轉(zhuǎn)載自微信公眾號(hào)「大遷世界」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系大遷世界公眾號(hào)。