Usage of the keyword in JavaScript:
The for-in loop should be used to traverse non-array objects. the for-in loop is also called "enumeration ".
Array elements are iterated but not recommended, because the order cannot be ensured. If an attribute is added to the Array prototype, this attribute will be traversed.
It is best to use a normal for loop for arrays, and use a for-in loop for objects.
For objects, the attributes of objects 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 has the following functions:
Definition:
The in operator is used to determine whether an attribute belongs to an object. It can be a direct attribute of an object or an attribute inherited by prototype.
Var Fn = function () {this. age = 1 ;}; Fn. prototype. name = 'Jim '; // Fn. prototype. age = undefined; var f = new Fn (); // hasOwnProperty // how can I determine whether an attribute is inherited ??? Console. log ('age' in f &&! F. hasOwnProperty ('age'); // age may exist in the prototype chain or may not exist. // If the attribute value is null or undefined, f. age cannot be determined.
For general object attributes, You need to specify the attribute name using a string.
For example:
var mycar = {make: "Honda", model: "Accord", year: 1998};"make" in mycar // returns true"model" in mycar // returns true
If you use the delete operator to delete an attribute, false is returned when you use in again, for example:
var mycar = {make: "Honda", model: "Accord", year: 1998};delete mycar.make;"make" in mycar; // returns falsevar trees = new Array("redwood", "bay", "cedar", "oak", "maple");delete trees[3];3 in trees; // returns false
If you set an attribute value to undefined but do not use the delete operator, use the in check to return true.
var mycar = {make: "Honda", model: "Accord", year: 1998};mycar.make = undefined;"make" in mycar; // returns truevar trees = new Array("redwood", "bay", "cedar", "oak", "maple");trees[3] = undefined;3 in trees; // returns true
The above is a detailed description of how to use the keyword in JavaScript introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!