The usage of for in and in in javascript

For...In declarations are used to loop/iterate the properties of an array or object.
1. For arrays, the elements of the array are iterated, and for objects, the properties of the objects are iterated;
var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[ 2] = "BMW"
for (x in mycars)
{
document.write(mycars[x] + "<br />")
} The
output is:
Saab
Volvo
BMW
2. Object example:
var obj = {
w: "wen" ,
j: "jian",
b: "bao"
}
for(var v in obj){
document.write(v)+"<br/>";
} The
output is:
w
j
b
3. Determine whether the object is an array/ Elements/attributes of object:
Format: (variable in object)...

  When "object" is an object, "variable" refers to the "property" of the object.
Array example:
var arr = ["a","b","2","3","str"];
var result = ("b" in arr);
var result1 = (4 in arr);
document. write(result+"<br>");
document.write(result1+"<br>"); The
output is:
false
true
4. Object example:
var obj={
w:"wen",
j:"jian",
b: "bao"
}
var result=(2 in obj);
var result1=("j" in obj);
document.write(result)+"<br/>";
document.write(result1)+"<br/> ";The
output is:
false
true

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325677887&siteId=291194637