(I) Dynamic selection method and attribute
In actual work, we often encounter this situation: call one of the two methods [1] according to a certain condition, or read and write operations on one of the two attributes [2]. The following code shows this:
The code copy is as follows:
if (condition) {
myObj.method1(someArg);
} else {
myObj.method2(someArg);
}
JavaScript provides a simple syntax that uses square bracket operators ([]) to dynamically select methods and properties. As shown in the following code, JavaScript has two equivalent member access syntax (this feature is common in dynamic languages):
obj[expressionResultingInMembername] == obj.memberName
If you have used integer subscripts to access an element in an array, you have already started using square bracket operators to make dynamic member selection. This is because the array object itself contains attributes (and length attributes) named after the number subscript. However, JavaScript does not allow you to directly access these properties using dot operators (.), so myArray.0 is syntactically illegal (it's a shame, it's a cool syntax).
Why are square bracket operators more powerful than dot operator notation? This is because you can access the member of the object using any content representing the member name in square brackets. These include literals, variables that hold member names, name combinations (mostly string splicing), and fast if/then selection using ternary operators (condition ? valueIfTrue : valueIfFalse). All of this content will be processed into a string, and then JavaScript will use this string to find the corresponding members.
Since a function in JavaScript is itself an object, it can be referenced like other values. If the result of an expression is a function, you can call it directly with the bracket operator, just like you call the function directly with the function name.
It should be noted that if you use this trick heavily on the parameters you pass to the method, the confusing parentheses may make the code difficult to read, and it is wiser to use the regular if/else structure at this time.
(II) JavaScript traversal object properties and methods
JavaScript uses the for in statement to iterate over the properties and methods of an object. The for in statement loops through a JavaScript object. Each time, it will obtain an attribute or method of the object.
grammar:
The code copy is as follows:
for(valueName in ObjectName){
// Code
}
Where, valueName is the variable name, which holds the name of the property or method. Each time the loop, the value of valueName will change.