javascript - property access using [] array notation -
i newbie js. reading definite guide , came through this, created player object this
var player= { name: 'the player', age: 33, address:'street 32' } var addr = ""; (i = 0; < 4; i++) { addr += player["address" + i] + '\n'; }
now book says loop add code reads , concatenates address0, address1, address2, , address3 properties of player object. not working..
to add 1 address
property player
object like
player.address = "some street 32";
if want add 4 "address fields"/ properties player
object:
var player={ name: 'the player', age: 33 }; (i = 0; < 4; i++) { player["address" + i] = "empty"; } console.log( player );
[object object] {
address0: "empty",
address1: "empty",
address2: "empty",
address3: "empty",
age: 33,
name: "the player"
}
though see no use-case of pre-creating properties you'll not use in future. rather create array of addresses (if need store more addresses) like:
player = { addresses = [], name = "the player" }
than whenever need add new address player like:
player.addresses.push("street 32"); player.addresses.push("newstreet 43"); console.log( player.addresses ); // ["street 32", "newstreet 43"] console.log( player.addresses[0] ); // "street 32"
than whenever want addresses can loop player.addresses
or if want newest address (the latest 1 in array) do:
var playerlatestaddress = player.addresses.slice(-1).pop(); // "mynew, street 43"
instead code does:
var addr = ""; // create empty string concatenate (i = 0; < 4; i++) { // 4 times.... // add `addr` value existent `player.addressn` property addr += player["address" + i] + '\n'; // error: player.address0 undefined }
therefore if test console.log( addr )
you'll get:
"undefined
undefined
undefined
undefined
"
Comments
Post a Comment