简体   繁体   中英

Sanitize javascript array element

Is there something i can do here

    const ecommerce = {
    purchase: {
        actionField: {
        },
    },
}

As it looks like, the inputted value is a string. You could convert the string to number by using an unary plus + in front of the variable.

name: "PRICEPLAN-" + +price,

An other way would include some sanity checks and urges the user to input a valid value.

@Nina Scholz' answer is correct and concise. The other way in JavaScript to do this, and which I personally prefer because it's more semantic, is to use Number() .

name: "PRICEPLAN-" + Number(price),

I find that good semantics make it easier for others to understand my code (and for me too, when I come back to it 6 months later.)

As others have pointed out, this will not coerce your values to an integer, so you will want to be sure about your inputs.

If you want Integer value, then you can use var parseInt() function in JS

var a = parseInt("10.00")

will convert it to "10"

radix : An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior.

After adding radix it will assure the output will be decimal :

var a = parseInt("010.00", 10)

To be sure to have an Interger, use parseInt() . As Number() won't prevent numbers like 3.11 to be transformed to Integers.

name: "PRICEPLAN-" + parseInt(price),

And using ES6 template notation:

name: `PRICEPLAN-${parseInt(price)}`,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM