(1) Dynamic selection of methods and attributes
In actual work, we often encounter this situation: calling one of the two methods [1] according to a certain condition, or between two attributes Read and write operations are performed on one of [2]. The following code shows this situation:
if (condition ) {
myObj.method1(someArg);
} else {
myObj.method2(someArg);
}
JavaScript provides a simple syntax, That is, use the square bracket operator ([]) to dynamically select methods and properties. As the following code shows, JavaScript has two equivalent member access syntaxes (this feature is common in dynamic languages):
obj[expressionResultingInMembername] == obj.memberName
If you have used Integer subscript to access an element in the array, then you have begun to use the square bracket operator for dynamic member selection. This is because the array object itself contains properties named with numeric subscripts (as well as the length property). However, JavaScript doesn't allow you to access these properties directly using the dot operator (.), so myArray.0 is syntactically illegal (too bad, it's a cool syntax).
Why is the square bracket operator more powerful than the dot operator notation? This is because you can access an object's members using anything that represents a member name within square brackets. These include literals, variables holding member names, name combinations (in most cases string concatenation), and fast if/then selection using the ternary operator (condition ? valueIfTrue : valueIfFalse). All of this content will be processed into a string, and then JavaScript will use this string to find the corresponding member.
Since functions in JavaScript are themselves objects, they can be referenced like other values. If the result of an expression is a function, you can call it directly using the parentheses operator, just like you would call a function directly using its name.
It should be noted that if you use a lot of such techniques on the parameters passed to the method, the confusing parentheses may make the code difficult to read. In this case, it is more sensible to use the regular if/else structure.
(2) JavaScript traverses object properties and methods
JavaScript uses the for in statement to traverse the object's properties and methods. The for in statement loops through the JavaScript object. Each time it loops, it will obtain a property or method of the object.
Syntax:
for(valueName in ObjectName){
// Code
}
Among them, valueName is the variable name, which saves the name of the attribute or method. The value of valueName will change every time it loops.