var obj ={
name:'nnn',
age:22,
job:'worker'
};
var arr=[
'name',
'age',
'job'
];
for (var i=0 ;i<arr.length;i++){
document.writeln(arr[i]+':'+obj[arr[i]]);
};//有值
for (var i=0 ;i<arr.length;i++){
document.writeln(arr[i]+':'+obj.arr[i]);
};//没值,不报错
What is the difference between these two, and what is the reason for the above situation? Please help me figure it out
Are you sure you are not reporting an error? Check the console information
obj.arr[i] This call is wrong
obj.arr does not exist, it is equal to undefined
undefined[i] An error will definitely occur
First of all, both obj and arr can be obtained using []:
The difference between the two methods in this example is:
obj[arr[i]] first takes arr[i] and then assigns it to obj[]:
obj.arr.[i] is to get obj.arr first, and then get [i] through obj.arr:
The square bracket operator can use the content of a string variable as the attribute name. The dot operator cannot.
One is an object and the other is an array, which are two completely different data structures
Can be used to traverse objects
As for the reason why you said no error is reported later, it is because of the three expressions of the for loop (the three separated by semicolons), obj.length is undefined and false, so the loop will not start. In addition, you can also give obj Try adding a length to the object, and the cycle will start
Friend, an error was reported...
The reason is:
Use obj[] to convert the incoming string into an attribute name, that is:
obj['name']==obj.name returns true
And The dot syntax of obj.'name' will not be automatically converted into obj.name, that is:
obj.'name'==obj.name error
I don't know if I understand it correctly...
It will definitely report an error, operator priority
The nesting is from the inside out
The chaining is from left to right
This sentence is right!