Reputation: 41
var logic = {
Rock: { w:"Scissors", l:"Paper"},
Paper: {w:"Rock", l:"Scissors"},
Scissors: {w:"Paper", l:"Rock"},
};
and it is used like:
logic[playChoice].w === rndChoice
Found it in a JS rock paper scissors example, curious what logic is called.
Please let me know if this is the wrong place...
Upvotes: 3
Views: 111
Reputation: 1820
Given:
var logic = {
Rock: { w:"Scissors", l:"Paper"},
Paper: {w:"Rock", l:"Scissors"},
Scissors: {w:"Paper", l:"Rock"},
};
logic[playChoice].w === rndChoice
logic
is an object. Just a regular object with the properties Rock
, Paper
, and Scissors
. Each of these properties are also objects, each with a win property (w
) and a loss property (l
). These properties are set to the string values of each available input.
The comparison (===
) uses two variables not previously defined, playChoice
, provided by the player and rndChoice
, provided by the computer. If the w
property for the object in the property for playChoice
equals the rndChoice
the comparison is true, and the player wins the round.
For example:
Rock
Scissors
w
property of logic["Rock"]
, or "Scissors"
Upvotes: 4
Reputation: 3281
The logic here is accessing an attribute of object "logic" with a given key.
The object "logic" here is a nested object, where the keys are in itself objects as well.
If playChoice === Rock
then we are accessing the Rock object from the logic object, and grabbing the "w" attribute from Rock.
Upvotes: 0
Reputation: 2748
If you are asking about the exact javascript structure that is being used here in the variable called logic
, to store the data, that is just a nested* object
, created via an object literal.
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
*: Meaning, that the values stored in the object are objects themselves as well.
In case you are curious about the more generic answer, things assigning values to keys are usually referred to as maps
. (When the values are consecutive numbers starting from zero, we essentially get an array
.)
I strongly recommend that you read through this to get a better understanding:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Upvotes: 2