Ver Mensaje Individual
  #3 (permalink)  
Antiguo 17/11/2014, 12:09
Avatar de Beatzoo
Beatzoo
 
Fecha de Ingreso: septiembre-2009
Ubicación: Retire Hill
Mensajes: 27
Antigüedad: 14 años, 7 meses
Puntos: 0
Respuesta: Dot Notation - Bracket Notation

Gracias por tu ayuda Alexis, ya tengo un poco más claro el uso de ambas. Pero aún no comprendo el tema de usar valores de variables como propiedades. En el siguiente texto hay dos ejemplos, el primero que no funciona y el segundo que sí. El primero usa notación por puntos para acceder a una propiedad almacenada en una variable y el segundo notación por corchetes. La cosa es que no comprendo muy bien por qué mediante la notación por puntos no puedo conseguir resultado (acompaño con el texto original del autor en inglés).

This feature of bracket notation becomes quite useful when you need to use a property name,
but it is stored in a variable (for example, when a value is sent as an argument to a function).
Since dot notation only allows the use of the bare property name, it cannot use a variable value:


Código Javascript:
Ver original
  1. var car = {
  2. seats: "cloth",
  3. engine: "V-6"
  4. };
  5. var s = "seats";
  6. function show_seat_type(sts) {
  7. window.alert(car.sts); // undefined
  8. }
  9. show_seat_type(s);

Here, rather than using the value of sts, a search for a property named sts within the car object
ensues, which results in a value of undefined being returned when the property is not found.
Using bracket notation, you can get this working:


Código Javascript:
Ver original
  1. var car = {
  2. seats: "cloth",
  3. engine: "V-6"
  4. };
  5. var s = "seats";
  6. function show_seat_type(sts) {
  7. window.alert(car[sts]); // works
  8. }
  9. show_seat_type(s);

This time, the value of the variable sts is used, which is the string “seats”, and “cloth” is
alerted to the viewer.