How to query whether a value is in an array using JavaScript? javascript Array
This article describes how to use JavaScript to query whether a value is in an array. We will share the content for your reference. I will not talk about it here. Let's take a look at the details:
Problem
> var b = ["aa", "bb"]> "aa" in b
I want to query whether the string aa is in the array. Is in feasible?
In
In operator first
If I have used python, I want to see if I can use in. Unfortunately, I cannot use it. First, let's look at the effect of python:
>>> a = ["aa" , "bb"]>>> "aa" in aTrue>>>
But JavaScript is different. The in operation object is an object, which is said on the MDN Official Website:
Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
In short:
1. Search for subscript for Arrays
2. The object can be key in obj, for example:
// Arraysvar trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];0 in trees // returns true3 in trees // returns true6 in trees // returns false'bay' in trees // returns false (you must specify the // index number, not the value at that index)'length' in trees // returns true (length is an Array property)Symbol.iterator in trees // returns true (arrays are iterable, works only in ES2015+)// Predefined objects'PI' in Math // returns true// Custom objectsvar mycar = {make: 'Honda', model: 'Accord', year: 1998};'make' in mycar // returns true'model' in mycar // returns true
IndexOf
This is a good thing and can be used directly. If it is used by the front end, make sure that the browser supports nodejs.
Instance:
> var b = ["aa", "bb"]undefined> "aa" in bfalse> b.indexOf("aa")0> b.indexOf("aaa")
The simplest and most crude method
It's just a for loop. Let's compare them one by one.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message to us. Thank you for your support.