/
Вопросы и ответы
/
JavaScript
/

Как проверить является ли переменная массивом js

Как проверить является ли переменная массивом js

4 года назад

Человек-Молекула

Ответы

1

Для того, чтобы проверить является ли переменная массивом, можно воспользоваться встроенным методом Array.isArray().

const numbers = [1, 2, 3];
console.log(Array.isArray(numbers)); // => true
console.log(Array.isArray([])); // => true

console.log(Array.isArray({})); // => false
console.log(Array.isArray('')); // => false

4 года назад

Ivan Gagarinov

0

Предлагаю воспользоваться оператором instanceof:

const letters = ['a', 'b', 'c'];
const number = 5;
const text = 'Dracaris!';
const user = { name: 'Vasiliy', age: 15 };
console.log(letters instanceof Array) // => true
console.log(number instanceof Array) // => false
console.log(text instanceof Array) // => false
console.log(user instanceof Array) // => false

Документация:

3 года назад

Виктория Аблаева

0

Предлагаю на рассмотрение такой метод:

const arr = [1,2,3,4,5]; const arrEmpty = []; const text = 'Text here'; const object = { name: 'Max', age: 30 }; const number = 5; console.log(typeof arr === 'object' && arr !== null && arr.length >= 0) // => true console.log(typeof arrEmpty === 'object' && arrEmpty !== null && arrEmpty.length >= 0) // => true console.log(typeof text === 'object' && text !== null && text.length >= 0) // => false console.log(typeof object === 'object' && object !== null && object.length >= 0) // => false console.log(typeof number === 'object' && number !== null && number.length >= 0) // => false

3 года назад