Manipulating Array Elements Post-Declaration in JavaScript

I have been searching for an answer to my question, but so far I haven't found anything. I am self-taught and have encountered a gap in my knowledge that is puzzling me.

In a complex setup of connected pieces, I have two globally-scoped variables (essentially static) and an array of character types outside the main onclick function:

var missingWut = ["child","spouse","talisman","relic","sock"];
var rdmmissingWut;
var pronounA = "he";
var charTypes = [
                  ["goatherd",pronounA+" wants to find a missing goat","kind"],
                  ["shepherd",pronounA+" wants to find a missing sheep","cruel"],
                  ["detective",pronounA+" wants to find a missing "+missingWut[rdmmissingWut],"spidery"],
                  ...,
                  ..., //this goes on for awhile; the array is currently 500 items long and has way more subindexes than I wanted/needed to include in this example.
];

The issue arises with the undefined variable rdmmissingWut at this point. To resolve this, we define rdmmissingWut inside the function, updating its value from undefined to a random index number:

rdmmissingWut = Math.floor(Math.random()*missingWut.length);
rdmcharType = Math.floor(Math.random()*charTypes.length);

We then assign a randomly chosen charType index to character 1 (char1).

var char1 = charTypes[rdmcharType];

My question is - Is there a way to update the variable value within the array without redefining the entire array after updating the variables?

One solution could be to redefine the array, which would update all variable values to their current values. However, this method seems cumbersome, cluttered, and inefficient.

Another scenario (with the same problem):

I intend to use the charTypes array to randomly select a character type for character 2 (char2) - and eventually for char3 & char4 as well. Suppose char2 (or 3 or 4) is female. After defining char1, I would need to change the value of pronounA to "she" and update all instances of it within the charTypes array before selecting a random charTypes index for her - am I correct? What would be the best approach to achieve this? Surely, there must be an elegant solution that I am unaware of.

Thank you for your assistance.

Answer №1

Make sure to assess that variable each time you loop through your array, suggesting a placeholder that can be swapped out using .replaceAll

var missingWut = ["child", "spouse", "talisman", "relic", "sock"];
var rdmmissingWut;
var pronounA = "he";
var charTypes = [
  ["goatherd", pronounA + " desires to locate a lost goat", "kind"],
  ["shepherd", pronounA + " wants to find a disappeared sheep", "cruel"],
  ["detective", pronounA + " wants to find a vanished _missingWut_", "spidery"]
];

function getMissingWut() {
  return missingWut[rdmmissingWut || 0]; // defaulting to zero if value not set
}
console.log(charTypes.flat().join("\n").replaceAll(/_missingWut_/g, getMissingWut()))

rdmmissingWut = 4

console.log(charTypes.flat().join("\n").replaceAll(/_missingWut_/g, getMissingWut()))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An Undefined Session: Leveraging Connect-Redis with ExpressJS and Node.js

Upon waking up this morning, I was greeted with an error message from Nodejitsu: Warning: connection.session() MemoryStore is not designed for a production environment, as it will leak memory, and will not scale past a single process. Determined to find ...

jQuery deduct a value from a given value

i have a full duration that is divided into multiple sections, the user needs to input the duration for each section i would like the system to calculate and display the remaining duration from the full duration, regardless of whether the user fills out ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

Create HTML content on the fly and ensure its validity

I am attempting to dynamically add a TextBox with the ID "tbComment" when the selected date is less than the current date on the client side, prior to hitting the submit button. Which approach would be the most effective in achieving this? I have tried us ...

Tips for incorporating css styles and javascript into handlebar files

I've been trying to figure out how to add styles and js to my handlebar files, but I'm hitting a roadblock. I attempted to use partials to store the stylesheet tags and then include those partials in the handlebars file, but it didn't work a ...

Preventing request interceptors from altering the request header value in Node.js

I am currently using the http-proxy-middleware to set up a proxy, and it is working smoothly. However, before I apply app.use('/', proxy_options);, I am attempting to intercept my request and update the request header. Unfortunately, the changes ...

Just ran $npm install and encountered an error message: "Module '../lib/utils/unsupported.js' not found."

Returning to work on a React project after switching from the Rails environment, I encountered an issue where I am unable to run NPM commands in my Mac terminal. Despite trying various solutions I found online, none seem to be effective. The real concern i ...

Obtain the OrbitControls view result from ThreeJS and set it as the default position

When implementing OrbitControls in ThreeJS, users can freely move the camera around. However, upon refreshing the model, the camera resets to its default position. I attempted to preserve the camera position and rotation using the code snippet below: camer ...

Unexpected results from Ruby's count() function when enumerating array elements

I thought the following ruby expressions were supposed to give the same result, but it seems like I overlooked something important. This bug needs to be addressed as it's too serious to ignore... # counts all elements in the array count = @quotation. ...

Combine two entities to create a new entity that mirrors the structure of the first entity

Can someone assist me with a data structure issue? Here are the objects I am working with: const elements = { item1: {color: 'blue', name: 'Item One' }, item2: {color: 'green', name: 'Item Two' }, item3: {colo ...

The background on my modal remains unchanged

I have integrated a modal using Iframe for user login/registration on my website. Here is the HTML code: <div class="modal" id="ays-popin-connexion" aria-hidden="true"> <div class="modal-body" aria-hidden="true"> <iframe src=" ...

Ways to trigger a JavaScript notification

I consider myself experienced in scripting, but I can't seem to figure this out. I'm trying to trigger a function on a button click event, so I decided to start by testing the buttonclick event with a basic window.alert. I wrote the following htm ...

Ways to choose tags that do not contain a particular tag within them

I am trying to utilize querySelectorAll to select all i elements that do not contain a font tag. The selector I attempted is: document.querySelectorAll('i > *:not(font)') <i> <font color="008000">Here goes some text</fon ...

Discover and analyze quantities across various columns in Excel when certain criteria are fulfilled

Within my data table, each row represents a client and every month I add a new column to indicate the type of orders they placed (A, B, or C). I am seeking to pinpoint clients who have made an order of type A at any point and then later switched to making ...

Oops! Looks like there's a hiccup with the express-validator plugin as the validation fails due to req.checkBody not being recognized as

Currently, I am setting up a post route to handle a submit request. The code snippet provided is from my user.js route: var express = require('express'); var router = express.Router(); var multer = require('multer'); var upload = multe ...

Make sure to give an item a little extra attention by highlighting or making it blink after it has

I have a collection of items that I utilize to construct an unordered list using ng-repeat. When a new item is added, I want it to stand out by blinking or having some kind of effect to grab the user's attention. While it would be easy with jQuery, I ...

Is it possible to initialize an array literal using variables in the C programming language?

I've been trying to figure out if it's possible to initialize an array literal with variables, but I haven't found a definitive answer. Just to give some context, my goal is to pass an array literal to a function. Here's the code snippe ...

What is the best way to send props to a React component?

Sorry for the inconvenience of asking for help with finding an issue in my code, but I'm facing challenges while learning React. I am attempting to pass a variable named hashRoute to a component in react. However, every time I try to access the prop ...

Creating a dynamic event set feature with a Collada object in A-Frame for immersive webVR experiences

I've been experimenting with creating a rotating animation on a collada object using the event set component plugin for A-frame. While I've had success with a-box, I'm running into some issues when trying to animate the collada object instea ...

What is the process for incorporating a unique Mongo expression into a JSON object?

I'm currently trying to figure out how to add a specific Mongo command to my JSON object. Normally, adding regular strings or objects is straightforward, but I'm struggling with this particular command: $set : { "author" : req.body.name } Simpl ...