javascript - Using a variable as identifier in a json array -
i'm wondering if possible use assigned variables identifier in json array. when tried this, getting unexpected results:
(code simplified, parameters passed in different way)
var parameter = 'animal'; var value = 'pony'; util.urlappendparameters (url, {parameter : value}); util.urlappendparameters = function(url, parameters) { (var x in parameters) { alert(x); } }
now alert popup says: 'parameter' instead of 'animal'. know use different method (creating array , assigning every parameter on new line), want keep code compact.
so question is: possible use variable identifier in json array, , if so, please tell me how?
thanks in advance!
no, can't use variable identifier within object literal that. parser expecting name there can't else provide string. couldn't this:
var parameter = 'animal'; var parameter = 'value'; //<- parser expects name, nothing more, original parameter not used name
the work around if really want use object literal on single line use eval:
util.urlappendparameters (url, eval("({" + parameter + " : value})");
Comments
Post a Comment