javascript---the advantage of accessing the properties of object as array(objects as associative arrays)

in javascript,we often use . operator to access the properties of an object like followings:

 

  
    
var obj = new myObj(); // initialize the obj with new
var myName = myobj.myName; // access the property with . operator

 

on the other hand,we can also access the properties of objects by [] operator just like accessiing the array;

 

 

 

  
    
var obj = new myObj(); // initialize the obj with new
var myName = myobj[ " myName " ]; // access the property with [] operator

 

what' is the difference between them?

in the first style,we access the property by the property name,the property name is a identifier.you know we can't change the property name,in other word ,we can't manipulate the identifier by program.

in the second,the property name is a string ,it is most important, it means we can access the properties of objects dynamicly.the property name can be manipulated and created while a program is running.

just seeing some example code:

 

  
    
var names;
for ( var i = 0 ;i < 4 ;i ++ ) // a loop
{
names
+= alex[ " name " + i] + ' \n ' ; // set the property dynamicly
}

 

in other situation,if the property name and corresponding value is not defined in the code,but comes from the input of the user,absolutely, we can't access the property and assign the value to it whith identifier of property name, because it doesn't exist. in this case,we can also use the [] operator to access the property and assign the value to it,example code is just as following:

 

代码
   
     
var inputValue = GetInputValueFromUser(); // get value
var inputProperty = GetInputPropertyFromUser(); // get property
obj[inputProperty] = inputValue; // it has done

// return the corresponding value
function GetInputValueFromUser()
{
return " testValue " ;
}

// /return the dynamic property
function GetInputPropertyFromUser()
{
return " testProperty " ;
}

 

since the user enters the property  at runtime.there is no doubt we can't know the property name ahead of time and also when we write the program.so there is no way to use . operator to access the property of the object.howere we can use [] operator with string value(it  can be changed  dynamicly at runtime).

so this is the advantage of using [] operator to access the properties of a object.

but if someone wants to  access the properties of object and doesn't use the [] operator,how should we do?don't worry,there is a way which can help us,we can use eval function ,which can make js complier treat a string as a js code,some example just seehttp://www.cnblogs.com/heaiping/archive/2010/06/16/1757962.html

你可能感兴趣的:(JavaScript)