Dynamic selection and traversal of JavaScript objects

  • 2020-03-30 02:21:40
  • OfStack

(I) dynamic selection methods and properties

In practice, we often encounter situations where one of two methods [1] is called based on a condition, or a read or write operation is performed on one of two properties [2]. The following code illustrates this situation:
if (condition) { 
} else { 

JavaScript provides a simple syntax that USES the square bracket operator ([]) to dynamically select methods and properties. As the following code shows, JavaScript has two equivalent member access grammars (a feature common in dynamic languages) :
Obj [expressionResultingInMembername] = = obj. MemberName

If you've ever used integer subscripts to access an element in an array, you've already started using the square bracket operator for dynamic member selection. This is because the array object itself contains attributes named after numeric subscripts (as well as the length attribute). However, JavaScript doesn't allow you to use the point operator (.) to access these properties directly, so myarray.0 is syntactically illegal (too bad, this is supposed to be a cool syntax).
Why is the square bracket operator more powerful than the dot operator notation? This is because you can access the members of an object using anything that represents the member name in square brackets. These include literals, variables holding member names, name combinations (mostly concatenation of strings), and the use of the ternary operator (condition? ValueIfTrue: quick if/then selection for valueIfFalse) implementation. All of this will be processed into a string that JavaScript will then use to find the corresponding member.
Since a function in JavaScript is itself an object, it can be referenced just like any other value. If the result of an expression is a function, you can call it directly with the parenthesis operator, just as you would call a function with its name.
It's important to note that if you use this technique a lot on the arguments you pass to methods, the messy parentheses can make the code hard to read, so it's wise to use the regular if/else structure.

(ii) JavaScript traverses 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 the JavaScript object, each time getting an attribute or method of the object.

for(valueName in ObjectName){ 
//  code  

Where valueName is the variable name that holds the name of an attribute or method, and the value of valueName changes each time through the loop.

Related articles: