Ask Your Question
3

What is a more effective method to verify the type of an Array containing elements of any type?

asked 2021-10-05 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-07-29 22:00:00 +0000

scrum gravatar image

One more effective method to verify the type of an Array containing elements of any type is to use the Array.isArray() method along with the Array.every() method. This method checks if the array is an array and if every element of the array satisfies a certain condition. For example, to verify if every element in the array is of type 'string':

let array = [1, 'hello', true];

if (Array.isArray(array) && array.every((element) => typeof element === 'string')) {
  console.log('Array is of type string');
} else {
  console.log('Array is not of type string');
}

This method checks if the array is an array and if every element in the array is of type 'string'. If every element satisfies the condition, it will return true, otherwise it will return false.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-05 11:00:00 +0000

Seen: 15 times

Last updated: Jul 29 '21