Substitution of "with" operator in strict mode

Let's say I have a user-entered string value stored in the variable f. For example:

f = "1/log(x)";

In vanilla JavaScript, I used the following operator:

f = "with (Math) {" + f + "}";

While this code worked perfectly fine in vanilla javascript, it caused issues when I switched to Vue.js and enabled strict mode. I'm not sure how to replace this operator now. Has anyone encountered this problem before and found a solution?

I tried the following approach:

            let math = Math
            math.f = f
            console.log(f)

Unfortunately, nothing seems to be working.

Answer №1

It's generally advised against using the 'with' statement as it can lead to problems in programs. So, what other options do you have?

You could define a series of global variables.

const sqrt = Math.sqrt
const log = Math.log

const test1 = new Function("a","return sqrt(a)")
const test2 = new Function("b","return log(b)")

console.log(test1(4))
console.log(test2(100))

Another option is to make replacements using regular expressions.

const fixMath = eq => eq.replace(/(sqrt|log|pow)/g,'Math.$1')

const test1 = new Function("a", fixMath("return sqrt(a)"))
const test2 = new Function("b", fixMath("return log(b)"))
const test3 = new Function("a", "b", fixMath("return pow(a, b)"))
const test4 = new Function("a", "b", fixMath("return sqrt(pow(a, 2) + pow(b, 2))"))

console.log(test1(4))
console.log(test2(100))
console.log(test3(10, 3))
console.log(test4(3, 3))

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

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

Is QA supported by LG WebOS 3.5 through webdriver?

I've been experimenting with Javascript ( nodejs ) and have successfully automated browser operations using selenium-webdriver on a local server. However, I am facing challenges when trying to automate tasks on my LG WebOS 3.5 TV. Does anyone know how ...

What is the correct way to define the field name in the update() function of Mongoose?

When attempting to update every field contained in the dataToChange object, I encountered a problem where the update() method does not take the key name from the outside. Instead, it looks for a "key" field within the database's object. How can I work ...

Issue with recognizing global methods in Vue and Typescript – help needed

I have a Vue mixin that looks like this: const languageMixin = Vue.extend({ methods: { $getLanguages: function(): object { return { en: 'english' } } } } Vue.mixin(languageMixin) ...

Integrating a series of Axios calls within a loop using asynchronous functions

Trying to figure this out is quite a challenge. I'm asking the user for a word and then checking its validity using an Axios API call. Once the validation is confirmed, the main loop of my game - hangman - begins with a delay between each move (hence, ...

Utilize Angular2 with ES6 modules while running an Express server

Having some issues using ES6 Modules with Angular2 in an app served by Node.js and Express.js. When attempting to load the Angular2/ES6 app in browser, encountered this error message in the FireFox console: The stylesheet http://localhost:8080/boot.css w ...

Create a user-friendly responsive tooltip in Javascript/jQuery with a convenient close

Looking to implement a tooltip feature that appears when a text box is focused on my responsive website, and disappears when it loses focus. Can anyone recommend the best JavaScript/jQuery library for this specific purpose? Here are my requirements: T ...

Tips for avoiding special characters when utilizing Jquery serialization?

I'm facing an issue with my form page where I need to perform some AJAX actions before submitting. The problem arises from the fact that the form input names contain period characters, which are causing conflicts in the AJAX functionality. Unfortunate ...

Incorporating a new method into the Object prototype to provide universal access across all modules

I've been delving into Typescript experimentation and I'm attempting to enhance the Object prototype by adding a property that can be accessed by all objects within my modules. Here's what I've developed so far: In a Common.ts file O ...

Combining Objects within an Array in JavaScript When Certain Conditions Are Satisfied

In my scenario, I am seeking assistance with merging the values of objects in an array if the id matches the warehouse_item_id. Specifically, there are two objects that need to be merged: id 191 and id 52 because id 52 has a warehouse_item_id of 191. Ple ...

Guide to adding a personalized HTTP header to ajax request using JavaScript or jQuery

Is there a way to create a custom HTTP header using JavaScript or jQuery? I've tried the code below but it's giving me an error of 405 Method not Allowed. I'm using the POST method, but in the request it shows as OPTION. The status code is ...

Exploring the World of JSON Nested Arrays with Unknown Titles and Organizing Them for Storage

Apologies if this question has already been addressed elsewhere, but I couldn't find it. I have a JSON object with dynamic keys: { "main": [ { "Example1": [ { "Example1_Var02": "5", ...

Stock Chart that resembles the functionality of Google's popular line chart feature

Can anyone recommend a Javascript or SVG chart library that has a style similar to a Google Chart? I have been searching without much luck and would appreciate some guidance on how to achieve a similar look. I've looked into the Google Visualization ...

Changing innerHTML in CoffeeScript

Are there other options instead of using the 'innerHTML' property in CoffeeScript? In JavaScript, you typically write something like this: document.getElementById('element').innerHTML = "blah_blah" Is there a different approach to ac ...

Utilizing Mantine dropzone in conjunction with React Hook Form within a Javascript environment

Can Mantine dropzone be used with React hook form in JavaScript? I am currently working on a modal Upload using Tailwind components like this import { useForm } from 'react-hook-form'; import { Group, Text, useMantineTheme } from '@mantine/c ...

Tips for adjusting the height of a div using the slideToggle function for expanding and collapsing content

Is there a way to modify my code in order to adjust the height of a <div> using slideToggle()? The current implementation works almost correctly, with one minor issue. When I click on one "read_more" and then click on another, it does not behave as e ...

Finding clarity amidst the chaos of require and export in Express.js (Node.js)

Is there a way to make my socket.io connection modular so that it can run once and be accessible anywhere? How can I export it? var server = require("http").Server(express); var io = require("socket.io")(server); server.listen(5000); io.on('connect ...

Load select box with options upon document load

After the document loads, I want to populate a select box with values from my database using ajax and jQuery. Can someone help me identify what's wrong with my code? <select class="form-control sec" id="sec" name="sec"> <option value="s ...

The only numbers that can be typed using Typescript are odd numbers

I am looking for a way to create a type in Typescript that can check if a value is an odd number. I have searched for solutions, but all I find are hardcoded options like odds: 1 | 3 | 5 | 7 | 9. Is there a dynamic approach to achieve this using only Types ...

Issue with iPhone CSS displaying differently on mobile devices

The CSS design does not display correctly on iPhone devices in real-life testing, even though it appears fine on browsers with mobile view emulators. Interestingly, the design also looks great on Android phones but encounters issues specifically on iPhones ...