The for-in loop should be used on a non-array object's traversal, and looping using for-in is also known as an "enumeration."
For arrays, iterating over array elements is not recommended, because the order is not guaranteed, and if a property is added to the array's prototype, this property is also traversed, so
The best array uses the normal for loop, and the object uses the for-in loop
For an object, the object's properties are iterated;
var obj = {
"Key1": "Value1",
"Key2": "value2",
"Key3": "Value3"
};
function Enumakey () {
for (var key in obj) {
alert (key);
}
}
function Enumaval () {
for (var key in obj) {
Alert (Obj[key]);
}
}
The In keyword in JavaScript also has the following effect
Defined:
The in operator is used to determine whether an attribute belongs to an object, can be a direct property of an object, or it can be an attribute inherited through prototype.
var Fn = function () {this.age = 1;};
Fn.prototype.name = ' Jim ';
Fn.prototype.age = undefined;
var f = new Fn ();
hasOwnProperty
How to tell if a property is inherited???
Console.log (' age ' in F &&!f.hasownproperty (' age '));
Age may exist on a prototype chain or may not exist
If the property value is null or undefined, then f.age cannot be judged at this time.
For generic object properties, you need to specify the name of the property with a string
Such as:
var Mycar = {make: "Honda", Model: "Accord", year:1998};
"Make" in Mycar//returns True
"Model" in Mycar//returns True
If you delete an attribute by using the delete operator, it returns false when in check again, such as:
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
If you set a property value to undefined, but you do not use the delete operator, the in check returns TRUE.
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
How to use the JS keyword in