JavaScript配列チェック方法
JavaScriptで変数が配列かどうかチェックする方法
JavaScriptでは、変数が配列かどうかをチェックする方法はいくつかあります。以下はそのうちのいくつかです。
Array.isArray() メソッド
最もシンプルで推奨される方法です。
const arr = [1, 2, 3];
const str = "hello";
if (Array.isArray(arr)) {
console.log("arr is an array");
} else {
console.log("arr is not an array");
}
if (Array.isArray(str)) {
console.log("str is an array");
} else {
console.log("str is not an array");
}
instanceof 演算子
オブジェクトのプロトタイプチェーンをチェックします。
const arr = [1, 2, 3];
const str = "hello";
if (arr instanceof Array) {
console.log("arr is an array");
} else {
console.log("arr is not an array");
}
if (str instanceof Array) {
console.log("str is an array");
} else {
console.log("str is not an array");
}
typeof 演算子 (ただし注意が必要)
typeof
演算子は配列を object
として返します。そのため、厳密なチェックには適していません。
const arr = [1, 2, 3];
const str = "hello";
if (typeof arr === "object") {
console.log("arr is an array");
} else {
console.log("arr is not an array");
}
if (typeof str === "object") {
console.log("str is an array");
} else {
console.log("str is not an array");
}
const arr = [1, 2, 3];
const str = "hello";
if (Array.isArray(arr)) {
console.log("arr is an array");
} else {
console.log("arr is not an array");
}
if (Array.isArray(str)) {
console.log("str is an array");
} else {
console.log("str is not an array");
}
const arr = [1, 2, 3];
const str = "hello";
if (arr instanceof Array) {
console.log("arr is an array");
} else {
console.log("arr is not an array");
}
if (str instanceof Array) {
console.log("str is an array");
} else {
console.log("str is not an array");
}
const arr = [1, 2, 3];
const str = "hello";
if (typeof arr === "object") {
console.log("arr is an array");
} else {
console.log("arr is not an array");
}
if (typeof str === "object") {
console.log("str is an array");
} else {
console.log("str is not an array");
}
const arr = [1, 2, 3];
const str = "hello";
if (Array.isArray(arr)) {
console.log("arr is an array");
} else {
console.log("arr is not an array");
}
if (Array.isArray(str)) {
console.log("str is an array");
} else {
console.log("str is not an array");
}
const arr = [1, 2, 3];
const str = "hello";
if (arr instanceof Array) {
console.log("arr is an array");
} else {
console.log("arr is not an array");
}
if (str instanceof Array) {
console.log("str is an array");
} else {
console.log("str is not an array");
}
const arr = [1, 2, 3];
const str = "hello";
if (typeof arr === "object") {
console.log("arr is an array");
} else {
console.log("arr is not an array");
}
if (typeof str === "object") {
console.log("str is an array");
} else {
console.log("str is not an array");
}
javascript arrays list