In order to have the 'hear' property of r function as an associative array, similar to PHP, a different approach is needed since JavaScript does not support associative arrays. Instead, JavaScript arrays are indexed by numbers.
Since r.head is treated as an object (arrays in JavaScript are objects), you can assign properties to it using
r.head["whatever property name"]="value"
. However, these added properties might not get serialized to JSON when using JSON.stringify because
r.head
is considered an array, and only the numbered index values will be serialized.
To resolve this issue, defining r.head
as an object will make sure that all properties are properly serialized by JSON.stringify.
function request(url) {
this.url = url;
this.head = {};
}
var r = new request("http://test.com");
r.head["cookie"] = "version=1; skin=new";
r.head["agent"] = "Browser 1.0";
document.write(JSON.stringify(r));
If you run the following code snippet in your browser's console (by pressing F12), you will observe that arrays are not serialized in the same manner as objects:
var b = [];
b.something=22
console.log(b.something);
console.log(JSON.stringify(b));//=[]
console.log(b.hasOwnProperty("something"))//=true
b = {};
b.something=22
console.log(b.something);
console.log(JSON.stringify(b));//={"something":22}
console.log(b.hasOwnProperty("something"))//=true