Javascript arrays

I understand how to do a 1D array in Javascript. Is there a way to do a 2D? Can someone provide an example?

I'm coming up with a game filled with NPC characters (each with a name, statistic, current attitude towards you, etc). I need a way to keep track of all this.

Thanks in advance.


I am not at all familiar with Squiffy, but in JavaScript I would do that as an array of dictionaries, like this:

const characters = [
  { name:"Fred", happy:6, met:false },
  { name:"Mary", happy:4, met:false },
  { name:"Horatio", happy:12, met:false },
]

characters[1].happy = 5;

Just to expand on the excellent answer by The Pixie.
In that answer we are setting Mary's happy score to 5 using:

characters[1].happy = 5;

That is a totally fine way to achieve that and in no way is wrong but it does require the programmer to keep track of the location of the various character information in the array.

The updateHappy function below does that same thing in a way that may be a little more intuitive to use (once the function is written). Hope it makes sense and prompts some even better ideas on how to use the idea in your story.

Please ask if any of it doesn't make sense.

var characters = [
  { name:"Fred", happy:6, met:false },
  { name:"Mary", happy:4, met:false },
  { name:"Horatio", happy:12, met:false },
]

// Defining the function.
function updateHappy(nameToUpdate, newHappyValue){
  for(character in characters){
    if(characters[character].name == nameToUpdate){
      characters[character].happy = newHappyValue;
      break;
    }
  }
}

// Calling the function.
updateHappy('Mary', 5);

Thanks, all. This gives me the missing link between what I was reading on the JavaScript pages and practical applications. With a little effort, a huge list of characters (and items) could easily be constructed.

Thanks!


Log in to post a reply.

Support

Forums