assigning variables to array object definition values.
nelsonm
7:24 pm on Nov 8, 2011 (gmt 0)
HI all,
in javascript, i've defined an array object:
var data = {"ipSTID": 0, "ipSVID": 0};
and reassigned the values using variables this way...
data.ipSTID = woSTID; data.ipSVID = wvSVID;
I know i Can i assign the variables to the values in the object definition like:
var data = {"ipSTID": woSTID, "ipSVID": wvSVID};
Is this way the preferred way?
Fotiman
8:40 pm on Nov 8, 2011 (gmt 0)
i've defined an array object
Actually, that's not an array, it's an object literal. A better comparison would be a Map, not an array. In your example, data is an object that contains 2 properties, ipSTID and ipSVID. With the first approach, you're assigning values to the individual properties of data. With the second approach, you're replacing the entire data object with a new object literal (and incorrectly including the "var" keyword again). The second method is riskier because you're replacing an entire object. In general, the first method is the one that I think probably makes more sense for most scenarios.
nelsonm
10:38 pm on Nov 8, 2011 (gmt 0)
I stand corrected, yes it's an object. However, how can the second method be riskier? In both cases, you're just replacing the value of the name/value pair not the whole object.
Fotiman
11:38 pm on Nov 8, 2011 (gmt 0)
It's riskier if data contains more data than what you're setting. For example, suppose you do this:
var data = {"ipSTID": 0, "ipSVID": 0}; data.ipSTID = woSTID; data.ipSVID = wvSVID; data.foo = "some value"; data = {"ipSTID": woSTID, "ipSVID": wvSVID};
In that case, the value of data.foo no longer exists, because I've replaced the entire data object with a new object.
nelsonm
1:31 am on Nov 9, 2011 (gmt 0)
Ok... i get it.
Well while i can't speak for anyone else, but i would never re-define the object once it's created.
i would define once even with external variables... var data = {"ipSTID": woSTID, "ipSVID": wvSVID};
then update elements individually... data.ipSTID = value3; data.ipSVID = value4;
However, i do believe you can append a new element to the end of the object.
Anyway, thanks for pointing out a possible shooting of the foot.
Fotiman
2:31 am on Nov 9, 2011 (gmt 0)
I generally agree with what you're saying. I would choose the first method (assigning values to the properties of the object) rather than the second method (assigning an entirely new object to the variable) in most cases. Of course, there are exceptions to every rule and it probably depends on what you're trying to do. For example, there may be cases where you WANT to replace the object. Neither method is really incorrect, it's a matter of finding which method is the most correct for your situation.