简体   繁体   English

清理javascript数组元素

[英]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. @Nina Scholz 的回答正确而简洁。 The other way in JavaScript to do this, and which I personally prefer because it's more semantic, is to use Number() . JavaScript 中的另一种方法是使用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.)我发现良好的语义让其他人更容易理解我的代码(对我来说也是如此,当我在 6 个月后回到它时。)

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如果你想要整数值,那么你可以在 JS 中使用 var parseInt() 函数

var a = parseInt("10.00")

will convert it to "10"将其转换为“10”

radix : An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. radix :一个介于 2 和 36 之间的整数,表示上述字符串的基数(数学数字系统中的基数)。 Specify 10 for the decimal numeral system commonly used by humans.为人类常用的十进制数字系统指定 10。 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() .要确保有一个 Interger,请使用parseInt() As Number() won't prevent numbers like 3.11 to be transformed to Integers.因为Number()不会阻止像3.11这样的数字被转换为整数。

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

And using ES6 template notation:并使用 ES6 模板符号:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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