it_is_a_literature it_is_a_literature - 2 months ago 5
Javascript Question

Why the parameter can't be passed properly when function called?

var collection = {
"5439": {
"album": "ABBA Gold"
}
};
function updateRecords(id, prop, value) {
if(prop !== "tracks" && value !== ""){
collection[id].prop=value;
}
return collection;
}
updateRecords(5439, "artist", "ABBA");


why the result is
Object { album="ABBA Gold", prop="ABBA"}
,not
Object { album="ABBA Gold",artist="ABBA"}
?

When to parse
collection[id].prop=value;
,the value of prop is artist,the value of id is 5439,so
collection[id].prop=value;
should parsed into
collection[5439].artist="ABBA";
,why not?

Answer

Use Bracket notation

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).

collection[id][prop] = value;

instead of,

collection[id].prop=value;
Comments