Get Programming with JavaScript - Listing 5.12

Listing 5.12 - Displaying a player's location via object properties

var player1; var player2; var showPlayerPlace; showPlayerPlace = function (playerName, playerPlace) { console.log(playerName + " is in " + playerPlace); }; player1 = { name: "Kandra", place: "The Dungeon of Doom", health: 50 }; player2 = { name: "Dax", place: "The Old Library", health: 40 }; showPlayerPlace(player1.name, player1.place); showPlayerPlace(player2.name, player2.place);

Further Adventures

Listing 5.12 - Displaying a player's location via object properties - Task 1

var player1; var player2; var showPlayerPlace; showPlayerPlace = function (playerName, playerPlace) { console.log(playerName.substring(0, 1) + " is in " + playerPlace); }; player1 = { name: "Kandra", place: "The Dungeon of Doom", health: 50 }; player2 = { name: "Dax", place: "The Old Library", health: 40 }; showPlayerPlace(player1.name, player1.place); showPlayerPlace(player2.name, player2.place);

The substring function gives part of the string it is attached to.

"Jahver".substring(0, 1) gives "J".

After Task 1, it's not clear what the two arguments in parentheses do, although the first is probably where to start harvesting the substring.

Listing 5.12 - Displaying a player's location via object properties - Task 2

var player1; var player2; var showPlayerPlace; showPlayerPlace = function (playerName, playerPlace) { console.log(playerName.substring(0, 2) + " is in " + playerPlace); }; player1 = { name: "Kandra", place: "The Dungeon of Doom", health: 50 }; player2 = { name: "Dax", place: "The Old Library", health: 40 }; showPlayerPlace(player1.name, player1.place); showPlayerPlace(player2.name, player2.place);

The substring function gives part of the string it is attached to.

"Jahver".substring(0, 2) gives "Ja".

"Jahver".substring(0, 3) gives "Jah".

"Jahver".substring(0, 4) gives "Jahv".

The second argument might be the number of characters to harvest or the index of the character at which to stop harvesting.

Listing 5.12 - Displaying a player's location via object properties - Tasks 3 & 4

var player1; var player2; var showPlayerPlace; showPlayerPlace = function (playerName, playerPlace) { console.log(playerName.substring(1, 2) + " is in " + playerPlace); }; player1 = { name: "Kandra", place: "The Dungeon of Doom", health: 50 }; player2 = { name: "Dax", place: "The Old Library", health: 40 }; showPlayerPlace(player1.name, player1.place); showPlayerPlace(player2.name, player2.place);

The substring function gives part of the string it is attached to.

"Jahver".substring(1, 2) gives "a".

"Jahver".substring(1, 3) gives "ah".

"Jahver".substring(1, 4) gives "ahv".

The first argument is the index of the character at which to start harvesting.

The second argument is the index of the character at which to stop harvesting.