Setting a variable at an inappropriate time

function generateEnemyStats(enemy) {
 //javascript:alert(en[0]+'\n'+generateEnemyStats(en[0])+'\n'+en[0])
 with (Math) {
  enemy[1]=round(enemy[1]*(.5+random()))
  enemy[2]=round(enemy[2]*(1+random()))
  for (var stat=0; stat<5; stat++) enemy[3][stat]=round(enemy[3][stat]*(enemy[3][stat]/2+random()*enemy[3][stat]/10))
  for (var skill=0; skill<enemy[4].length; skill++) random()<it[enemy[4][skill]][3]/10?enemy[4][skill]=0:0
  }
 return enemy
 }

This script is designed to generate statistics for an enemy based on their base values in an RPG game. However, there seems to be an issue where the function not only returns the new stats, but also modifies the original enemy array. This can lead to unexpected results, such as weak enemies becoming incredibly powerful. How can I prevent this function from altering the enemy array stored in the 'en' array?

Answer №1

JavaScript operates on pass by reference for objects. This means that modifications made to the array a within the function genEnemy will be directly reflected on the original array. To avoid this, it is important to create a deep copy of the array and return this duplicated version. Below is a custom function that accomplishes this:

function duplicateArray(a) {
  var b = [];
  for (var i = 0; i < a.length; i++)
    if (a[i] instanceof Array)
      b[i] = duplicateArray(a[i]);
    else
      b[i] = a[i];
  return b;
}

Inside genEnemy, you should execute the following code:

a = duplicateArray(a);
// Perform alterations on the new array
return a;

Furthermore, remember to add semicolons to your code. Although they are not strictly required, omitting them may result in unexpected issues.

Answer №2

Make sure you are passing the array 'en' to the getEnemy() function. Remember, when passed by reference, the function will modify the values in the 'en' array directly.

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

JavaScript: Searching for multiple parameters is not possible - when using asynchronous functions, only the first parameter is returned

I've been struggling with this issue for a whole day now: I'm working on a website where I can input contacts into a SQLite database. My goal is to be able to query the database by either studentID or last name (nachname in German). I have an API ...

How can images be resized according to screen resolution without relying on javascript?

Looking to use a large banner image on my website with dimensions of 976X450. How can I make sure that the image stretches to fit higher resolution monitors without using multiple images for different resolutions? ...

A guide to adding a picture to AWS S3 with the help of GraphQL

When trying to upload a base64 string via GraphQL, I encountered an issue. It seems that if the string exceeds 50,000 characters, GraphQL fails to reach the resolve function without giving any error messages. However, when the string is less than 50,000 ...

When subscribed to, the BehaviorSubject will return the object twice

When working with a bank API for payments, the response expected by the banks is that Ban Pay JavaScript will perform an HTTP redirect in the top frame to a completeUrl. The question arises - what should be the completeUrl that I need to provide to the ban ...

Get the Zip file content using PushStreamContent JavaScript

I am looking for the correct method to download a PushStreamContent within a Post request. I have already set up the backend request like this: private static HttpClient Client { get; } = new HttpClient(); public HttpResponseMessage Get() { var filenames ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

Having difficulty in compressing Vue.js application

My Vue.js Application contains the following code snippet: (function() { initApp(); })(); function initApp() { window.myApp = new Vue({ el: '#wrapper', data() { return { somedata: [] } } }); } & ...

Securing client-side code with AngularJS for enhanced security

It's a known fact that once browsers have downloaded frontend files, there's no way to hide code from the client. However, I've heard that clients can debug JavaScript code, add breakpoints, skip code lines (especially security checks), and ...

Animating with JavaScript

I have a members button on my website that triggers a dropdown animation when clicked. However, the issue is that the animation occurs every time a page is loaded, even if the button is not clicked. I want the dropdown to only open when the button is click ...

Tips for integrating JQuery into a JavaScript file seamlessly without causing conflicts

Similar Question: Dynamically Including jQuery using JavaScript if it's not already present I am currently working on a project that requires users to embed a piece of javascript code on their websites, similar to Google Analytics. My main concer ...

Using an image within the input group in Bootstrap 4

I'm a beginner in web development and I'm currently utilizing the glyphicon. This is how I'm currently using it: const className = `form-group ${touched && error ? 'has-danger' : ''}`; <div className={classN ...

The code for populating the lookup does not perform as expected on the initial attempt

I've encountered an issue with my JavaScript code on a form where it auto populates 2 lookup fields with the current user when the record is being created. Most of the time, this function works as intended. However, I've noticed that during the f ...

Encountered an issue while trying to divide an array into two

Currently, I am faced with the task of removing the initial 16 bytes from my byte array. In my quest to achieve this, I turned to a post on Stack Overflow for guidance, which led me to the following code snippet: // Separate message into IV and encrypted ...

Differences between React class properties and ES6 class properties

With React 16.2, defining class properties is done differently with the tagLine example shown below: class Header extends React.Component { tagLine = "Super Hero"; render() { .... } } Contrastingly, in ES6 classes, it's not possible to define ...

What steps should I take to transform the chart data generation process during an AJAX callback?

I have created a code that generates a highchart chart, but now I want to convert the data used to create the chart into an AJAX Callback. This way, I can turn my chart into a live chart that updates every minute, and the only way to achieve this is thro ...

Having trouble implementing min and max date validation in Angular UI-Bootstrap datepicker with UI-Bootstrap version 1.3.3

My goal is to implement validation in my datepicker, preventing the user from selecting a date within 30 days before or after the current date. Here's the code snippet I'm currently using for the datepicker: <div class="form-group" ng-class=" ...

How can you calculate the number of elements in a jQuery array and iterate through each of them?

After extracting a string from a mySQL query with PHP, my AJAX script comes into play. This string is then dissected and placed into a jQuery array. The results are displayed on the screen using .html() The length of this array can range from zero items t ...

Can the fluctuations in resolution of webRTC streaming video be detected?

We are currently working on a project involving WebRTC and have specific requirements that involve detecting when the resolution of the streaming video (remote stream) changes in WebRTC. Is there a way for us to achieve this? Any tips or guidance would be ...

Executing a JavaScript function within a React web application

Having trouble calling JS functions from ReactJS? I recently encountered an issue when trying to import and call a JS function in a button onClick event in my React project. Specifically, when trying to use this.abtest.events.on in the handleButtonColor fu ...

Ruby - Identifying the presence of various values in an array at any position

I created a challenging text game where the final door is locked and requires three specific items (represented as Strings in an array) to unlock. In order to check if these key items are present in the player's inventory (which can hold various item ...