String arrays in Javascript with arithmetic operators

I am working with an array that contains mathematical signs.

var signs = ['+', '-', '*', '/'];

In addition, I have two variables representing digits to combine with each sign from the array.

var right_digit = 1;
var left_digit = 5;

I am curious if it is possible to perform the following operation in JavaScript:

var answer = left_digit + sign[0] + right_digit;

Answer №1

To steer clear of using eval, consider implementing a method similar to this:

var operators = {
    '+': function(operand1, operand2) { return operand1 + operand2; },
    ...
};

var calculatedAnswer = operators['+'](first_num, second_num);

Answer №2

It seems unlikely that you can directly accomplish this task, but you could create a function to handle it.

function performOperation(x, y, z) {
    switch (z) {
        case "+":
            return x + y;
        case "-":
            return x - y;
        case "*":
            return x * y;
        default:
            return x / y;
    }
}

Answer №3

If you need to dynamically evaluate operators, you can accomplish this using eval:

var result = eval(second_num + operation[0] + first_num);

However, keep in mind that using `eval` is not recommended due to potential security vulnerabilities (especially with untrusted data) and performance issues as the code needs to be analyzed each time it's executed.

Alternatively, a better approach would be to use a switch statement like the following:

function calculate(x, operator, y) {
    switch (operator) {
      case "+":
        return x + y;
      case "-":
        return x - y;
      case "*":
        return x * y;
      case "/":
        return x / y;
    }
}
var result = calculate(second_num, operation[0], first_num);

Answer №4

One approach is to utilize the eval function:

var result = eval(first_number + operator[0] + second_number);

Answer №5

An effective method using eval (it removes digits and symbols, throwing an error for incorrect format):

function performCalculation(expression) {
    var matches = /^(\d+)([+\-*/])(\d+)$/.exec(expression);

    if(!matches) {
        throw "Invalid expression";
    }

    return eval(matches[1] + matches[2] + matches[3]);
}

performCalculation('2*4'); // 8

This allows you to execute:

performCalculation(left + operation + right);

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

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

Retrieve the property by mapping the click event

I am looking for a way to retrieve the ID of a specific item when a link button inside a mapped list is clicked. How can I achieve this functionality? idFinder(){ console.log('ID:', item.id); } this.sampleData = this.state.data.map((item, ...

Ways to display all current users on a single page within an application

I have come across a project requirement where I need to display the number of active users on each page. I am considering various approaches but unsure of the best practice in these scenarios. Here are a few options I am considering: 1. Using SignalR 2. ...

The background image is not appearing on the div as expected

I've been attempting to create a div and set a background image for it using jQuery, but I seem to be facing issues. When I try setting the background color to white, it works fine. Here's the code snippet: function appendToDom(poster) { ...

Retrieve a result from a setTimeout function

Can someone assist me with storing the status value in a variable named 's'? Any help would be greatly appreciated. Below is the code snippet: let s = setTimeout( ()=>{ this.matchService.getMatches().subscribe(ms => { this.match ...

Retrieving information and implementing condition-based rendering using React's useEffect

I am currently developing a MERN stack application that retrieves information regarding college classes and presents it in a table format. The CoursesTable.js component is structured as follows: import React, { useState, useEffect } from 'react'; ...

Listener for a special event in Three.js

As I embark on my journey with Three js, I find myself in search of a unique event listener that seems to elude me online. I am curious whether it is feasible to execute a specific action when the first-person viewer enters an object. Any advice would be ...

Obtain a string in JSON format upon clicking in Angular 2

I am working on extracting the title from a json response using a click event. Currently, I can retrieve all the titles when the button is clicked, but I am looking for a way to obtain a specific title based on the button or a href that the user has clicke ...

What is the internal mechanism behind the operation of JavaScript function parameters?

As someone who is new to programming, I've been struggling to understand how parameters and arguments work behind the scenes. For example: function changeStuff(a) { return a = a * 10; } var num = 10; console.log(changeStuff(num)); / ...

Utilizing jquery to showcase the information in a neat and organized table

Having an input text box and a button, I am looking to display dummy data in a table when any number is entered into the input field and the button is clicked. Here is what I have tried: My Approach $("button#submitid").click(function () { $(&quo ...

Can the functionality of ngIf and async pipe be replicated within the component's code?

With a form component and a thank you page, I am faced with the challenge of sharing data between these two components using rxjs ReplaySubject. The full code listings can be found here. In my implementation, I am utilizing ngIf and the async pipe to hand ...

Designing an intricate layout with the help of Bootstrap-Vue

After exploring the Vue-Bootstrap panel in my previous question, I implemented the following code snippet to generate a panel: <b-card no-body class="mb-1"> <b-card-header header-tag="header" class="p-1" role="tab"> <b-button b ...

The NodeJS server experiences a crash immediately after attempting to save data into the MongoDB database

I have encountered an issue with a script that saves objects to a MongoDB database using mongoose. The object is successfully saved to the database, but immediately after, the server crashes and throws the error message: catch(err) { process.nextTick(funct ...

Populate an HTML table using a JavaScript array containing objects

Greetings, fellow coders! I am new to the coding world and this community, and despite my efforts in searching for a solution, I couldn't find exactly what I was looking for. So, here is my question: I have an array structured as follows: const arr ...

JEST does not include support for document.addEventListener

I have incorporated JEST into my testing process for my script. However, I have noticed that the coverage status does not include instance.init(). const instance = new RecommendCards(); document.addEventListener('DOMContentLoaded', () => ...

Connect an AngularJS UI-Select to a UI-Grid filter

I am working on integrating AngularUI's ui-grid and ui-select together. This allows me to utilize ui-select functionality while filtering the ui-grid data. I have made some progress with a Plunker example that can be found here: http://plnkr.co/edit/ ...

New features in Next.js 13 include an updated server component and enhanced fetch capabilities for re

Is it possible to toggle the URL from the getData function? I have my main page component with JSON todos. Can I replace 'todos' with 'users' in my client component? import styles from './page.module.css' import Button from "@ ...

javascript mysql and php clash when it comes to loading

I am encountering an issue where I cannot fetch data from my phpMyAdmin database using php code when loading the map api that utilizes javascript. Currently, only the map javascript is being loaded. I have valuable data stored in my database and any assis ...

Ways to access customer subscriptions in Stripe

I have a customer on Stripe who wants to cancel his subscription. I have checked the documentation for the customer object (here) and the subscription object (here), but I am unsure how to retrieve the subscription id associated with the customer. In order ...

What is the best way to retrieve the values from the labels for two separate buttons?

I designed a pair of buttons with a single label below. Both buttons acted as standalone entities. <label for="buttons" class ="val">0</label> <input class="btn btn-primary button1" type="button" ...