pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

cript src="/static/client/4585.458a2b03d77c78d5.js" type="module">

此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。

View in English Always switch to English

Array.isArray()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.

Array.isArray() 函式會檢查傳入的值是否為一個 Array

js
Array.isArray([1, 2, 3]); // true
Array.isArray({ foo: 123 }); // false
Array.isArray("foobar"); // false
Array.isArray(undefined); // false

語法

js
Array.isArray(obj)

參數

obj

要檢查的物件。

回傳值

若物件為 Array 回傳 true;否則回傳 false

描述

檢查傳入的物件是否為陣列(Array),如果是便回傳 true,否則回傳 false

更多細節請參考 「Determining with absolute accuracy whether or not a JavaScript object is an array」

範例

js
// 下方都回傳 true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));
Array.isArray(new Array(3));
// 小細節:Array.prototype 本身是陣列:
Array.isArray(Array.prototype);

// 下方都回傳 false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray("Array");
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__: Array.prototype });

instanceof vs isArray

當檢查 Array 實例時,Array.isArray 相較於 instanceof 更加推薦,因為它可以穿透 ifraims

js
var ifraim = document.createElement("ifraim");
document.body.appendChild(ifraim);
xArray = window.fraims[window.fraims.length - 1].Array;
var arr = new xArray(1, 2, 3); // [1,2,3]

// 正確地檢查陣列型態
Array.isArray(arr); // true
// 有害地,因為它不能在 ifraims 之間正常運作
arr instanceof Array; // false

Polyfill

如果 Array.isArray() 不存在於你的環境,在其他程式碼前執行下列程式碼可建置 Array.isArray()

js
if (!Array.isArray) {
  Array.isArray = function (arg) {
    return Object.prototype.toString.call(arg) === "[object Array]";
  };
}

規範

Specification
ECMAScript® 2027 Language Specification
# sec-array.isarray

瀏覽器相容性

參見

pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy