javascript - js object value
天蓬老师
天蓬老师 2017-05-19 10:33:49
0
6
697
  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

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(6)
黄舟

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[]:

arr[i]==> 'name' ==> obj['name'] ==> 取值成功

obj.arr.[i] is to get obj.arr first, and then get [i] through obj.arr:

obj.arr==> undefined ==> undefined[i] ==> 报错
嵌套的由内而外
链式由左往右
淡淡烟草味

The square bracket operator can use the content of a string variable as the attribute name. The dot operator cannot.

var a={
    name:1
}
var str="name";
console.log(a[str])//1
console.log(a.str)//undefined
巴扎黑

One is an object and the other is an array, which are two completely different data structures

Can be used to traverse objects

for (var i in obj) {
    console.log(obj[i])
}

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...

过去多啦不再A梦

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!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template