Objeto JavaScript como matriz

Accessing Js object properties :

Cuál es la diferencia entre :

1) Obj.src
     vs
2) Obj["src"]

I only know that #1 can't be used with number ( e.g. if the property name is "1")

Is there any other major differences ?

preguntado el 31 de julio de 12 a las 11:07

@Dennis well , sort of duplicate. I didnt see the remark that dot notation no puedes be used with number. ( very important) -

You're right, my bad. I assumed a link titled "characters that can't be used with dot notation" would include a list of characters that can't be used with dot notation. -

4 Respuestas

No difference really. Old'ish browser showed some performance differences using either the one or the other notation, but those times are over.

The only important difference is that the bracket notation is your only chance to dinamicamente access Object properties.

Por ejemplo:

var access = 'src';

Obj[ access ];

you can't do that using a dot notation.

Respondido 31 Jul 12, 11:07

No hay diferencia entre Obj.src y Obj["src"].

But when the property name is a variable, you could only use the second way to access it.

var name = "src";

Entonces necesitas usar Obj[name], Obj.name will try to access the property with the name of name.

Respondido 31 Jul 12, 11:07

En javascript, every object is an matriz asociativa.

I can't think of much more to add besides its one of the mejor magical features of JavaScript. :)

Respondido 31 Jul 12, 11:07

The set of properties that can be accessed with bracket notation is a superset of the properties that can be accessed with dot notation. Anything accessed with the dot must be a identificador de JavaScript válido:

a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number.

Properties can still be strings that are not identifiers, but require bracket notation for access:

object["I have whitespace"];
object["1startswithanumber"];
object["Punctuation!!??"];
object[""] = "empty string";
// not an exhaustive list

ES5 allows you to use reserved words as properties, x.class = "some string", sin embargo this is not allowed by ES3, so you should probably use brackets x["class"] for backwards compatability.


Bracket notation can still be used to access valid identifier properties but dot notation is considered cleaner. Brackets are generally used when you have a variable:

object[input.value];  //Retrieves the property named by the value of the input field

Functions can also be accessed with brackets:

var fn = operation == "tag" ? "getElementsByTagName":"getElementsByClassName";
document[fn](str);

Respondido 31 Jul 12, 12:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.