The In operator of JavaScript ("How to tell if a value is an element in an array"?) )

Source: Internet
Author: User

When you write JavaScript, you encounter a common question, "How can I tell if a value is an element in an array"? This reminds me of the In_array () function in PHP and the in operator in Python. But JavaScript does not seem to have a similar function built into it, and its in operator has a slightly different effect. By querying the relevant data, I found that the JavaScript in operator is useful.

First, the question
Let me think of the in operator because of the question: "How can I tell if a value is an element in an array"?
In PHP, you might be able to handle this:

$os = Array ("Mac", "NT", "Irix", "Linux");
if (In_array ("Irix", $os)) {
echo "Got Irix";
}


In Python, this might be the case:

val = 17
If Val in [1,4,5,7,12,14,17,20,34]: print "yes"


How do you do that in JavaScript? Let's take a look at the description of the in operator.

Two, in operator
Now when I write JavaScript, I like to refer to two places: MDC's core JavaScript 1.5 Reference and W3Schools's JavaScript Tutorial.
From here, you can find a description of the in operator. It is visible that the in operator in JavaScript operates on object (objects) and is not intended for arrays.
1. Simple usage
The right side of in must be an object variable, for example:

var Mycar = {make: "Honda", Model: "Accord", year:1998};
if ("make" in Mycar) document.write (' true ');
else document.write (' false '); Display True


2. Incorrect usage
If we use the in array for the judgment, it will produce the wrong result:

var trees = new Array ("Redwood", "Bay", "Cedar", "oak", "maple");
if ("oak" in Trees) document.write (' true ');
else document.write (' false '); Show False


In turn, we treat the trees array as an object and then judge the elements in the object, for example:

if (0 in trees) document.write (' true ');
else document.write (' false '); Display True
document.write (trees.length); Displays the value of the length property of the Trees array object: 5
if (' length ' in trees) document.write (' true ');
else document.write (' false '); Display true because length is a property of the trees array object


Three, the correct method of judging the logarithm group
Although the in is directly used to judge an array, it produces incorrect results, but there is no way to avoid it. Proper use of the in operator can be convenient.
1, through the cycle to solve the problem
In fact, this is the most basic way to deal with "how to determine whether a value is an element in an array" problem:

function In_array (Searchstring,array) {
for (i=0;i<array.length;i++) {
if (searchstring = = Array[i]) return true;
}
return false;
}
if (In_array (' oak ', Trees)) document.write (' true '); Display True
else document.write (' false ');



2. Proper use of In operator
Now that we know that in can be used to judge an object's property value, we can also map array one by one to the object's properties and then use in. The following code is referenced from: here.

function oc (a)
{
var o = {}; Equivalent to var o = new Object ();
for (Var i=0;i<a.length;i++)
{
O[a[i]]= "; Note that the wording cannot be written as O.a[i]
}
return o;
}
if (' Oak ' in OC (trees)) document.write (' true '); Display True
else document.write (' false ');
o = OC (trees);
if (o.oak! = ' undefined ') document.write (' true '); Display True
else document.write (' false '); True
if (o[' oak ']! = ' undefined ') document.write (' true '); Display True
else document.write (' false '); True


Here, the OC function converts an array into an object and takes the elements of the array as attributes of the object (the value is an empty string), and then uses the in operator to judge.
※ Note: usually Obj.key and obj[' key ' can be exchanged, but in for (;;) and for (in) statements, the object property is written in obj[' key ' instead of Obj.key.

3. Skillfully using in operator
In addition to being able to borrow the in operator in the case of arrays, we can also use the in feature to simplify how the IF statement is written in multiple "or" condition cases.
For example, the following sentence:

if (foo = = ' Bar ' | | foo = = ' Foobar ' | | foo = = ' foo ')
{
//...
}


Can be written as:

if (foo in {' Bar ': ', ' foobar ': ', ' foo ': '})
{
//...
}


The results of the judgment are identical.

Iv. Matters of note
When using the in operator, it is important to note that in addition to carefully differentiating between arrays and objects:
1, in-oriented must be an object
For example, the following is the judgment of a string:

var color1 = new String ("green");
"Length" in Color1//returns True
var color2 = "Coral";
"Length" in Color2//generates an error (color was not a String object)


Because JavaScript differs from Python, strings cannot be processed directly as string objects. FireFox will be reported "invalid ' in ' operand Color2", IE will be reported "missing objects."

2, Object properties are deleted (deleted) or undefined (undefined) The result is different
Delete the object's property values with delete:

var Mycar = {make: "Honda", Model: "Accord", year:1998};
Delete Mycar.make;
' Make ' in Mycar; Returns false

var trees = new Array ("Redwood", "Bay", "Cedar", "oak", "maple");
Delete Trees[3];
3 in trees; Returns false


Set the object property value to undefined:

var Mycar = {make: "Honda", Model: "Accord", year:1998};
Mycar.make = undefined;
' Make ' in Mycar; Returns True
var trees = new Array ("Redwood", "Bay", "Cedar", "oak", "maple");
TREES[3] = undefined;
3 in trees; Returns True


3. Associative arrays
Since arrays can be converted to objects, we can think of JavaScript objects as "associative arrays" (similar to dictionaries in Python, hash in Perl), whereas ordinary array elements correspond to the object's properties (Null values).

var onearray=new Array ();
onearray["Firstkey"]= "Firstvalue";
onearray["Secondkey"]= "SecondValue";
var oneobject={};
Oneobject.firstkey= "Firstvalue";
Oneobject.secondkey= "SecondValue";
For (key in Onearray) {
document.write (key+ ' = ' +onearray[key]);
}
For (key in Oneobject) {
document.write (key+ ' = ' +oneobject[key]);
}


In this way, there are the following advantages:

Reference A, we can be very convenient to use in to determine whether the element is in the object;
B, the object retrieves a property, for example: o[' Oak ', whose time complexity is O (1), and to find an element in the array, the time complexity of O (n).


However, it is not said that all arrays can be replaced with objects. At a minimum, the elements in the array must be required to be unique.
For example, the following array:

var trees = new Array ("Redwood", "Bay", "Cedar", "oak", "maple", "oak");


Because the "oak" element repeats, it cannot be converted directly to an object.

4. Efficiency issues
According to the introduction, see: here. Which proposed:
The traversal efficiency of the collection (high to Low) is: var value = Obj[key]; > for (;;) > for (in).
So, if the array can be substituted with the object (the value is unique), the object form should be preferred. When encountering "Determine whether a value is an element in an array", the value is directly judged Obj.key = = ' undefined ', or if (' key ' in obj). Otherwise, use for (;;) Way to judge it.
(The object has no length and cannot be used for (;;) Loop, can only be used for (in))
Also, in: here, there is an efficiency problem that iterates over an array. It is proposed that, before the loop, the length of the array is first assigned to a variable, the loop is called directly, so the efficiency will be higher.

The In operator of JavaScript ("How to tell if a value is an element in an array"?) )

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.