difference between object.property vs. object [property]

3
    /*  property01.js
    define propiedades de un objeto
*/

var o = {a:1, b:2, c:3, d: 4};

for (var i in o) {  
    console.log('o[' + i + ']: ' + o[i]);  
    console.log('o.' + i + ': ' + o.i);  
}  
/* salida  
o[a]: 1  
o.a: undefined  
o[b]: 2  
o.b: undefined  
o[c]: 3  
o.c: undefined  
o[d]: 4  
o.d: undefined  
*/

question: because o.a, o.b, o.c and o.d give indefinite

    
asked by jab70 05.12.2018 в 23:04
source

1 answer

3

You are wrong in your approach. You are not trying

o.a

otherwise

o.i

In your code

console.log('o.' + i + ': ' + o.i);

that is the difference between using [ ] and not using it:

  • o[i] - > Evaluate i and use that value to search within o .

  • o.i - > does not evaluate i ; It is taken literally.

You can easily check if you do

var o = {a:1, b:2, c:3, d: 4, i: '¡ Es verdad' };
    
answered by 05.12.2018 / 23:09
source