从 Jquery var 的末尾修剪“px”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3624863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
trim "px" off the end of Jquery var
提问by phil crowe
I have a variable which stores the css value of a margin. I want to remove the "px" from the end so that i just have the number to work with. How can i do this?
我有一个存储边距的 css 值的变量。我想从末尾删除“px”,以便我只有可以使用的数字。我怎样才能做到这一点?
回答by Alex Reitbort
var x = "1px";
var y = parseInt(x, 10); // specify radix to prevent unpredictable behavior
回答by Arman Nisch
Option 1:
选项1:
parseInt('200px', 10);
The parseInt() function parses a string and returns an integer. Don't change the 10 found in the above function (known as a "radix") unless you know what you are doing.
parseInt() 函数解析一个字符串并返回一个整数。除非您知道自己在做什么,否则不要更改上述函数中的 10(称为“基数”)。
Outputwill be: 200.
输出将为:200。
Option 2(I personally prefer this option)
选项2 (我个人更喜欢这个选项)
parseFloat('200px')
Outputwill be: 200
输出将为:200
The parseFloat() function parses a string and returns a floating point number.
parseFloat() 函数解析一个字符串并返回一个浮点数。
The parseFloat() function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.
parseFloat() 函数确定指定字符串中的第一个字符是否为数字。如果是,它会解析字符串直到到达数字的末尾,并将数字作为数字而不是字符串返回。
The advantage of Option 2 is that if you use decimal numbers (e.g. 200.32322px) you will get the number returned with the values behind the decimal point. Useful if you need specific numbers returned.
选项 2 的优点是,如果您使用十进制数字(例如 200.32322px),您将获得返回的数字以及小数点后面的值。如果您需要返回特定数字,则很有用。
回答by Rob Olmos
Using the String.replace() method is an easy way:
使用 String.replace() 方法是一种简单的方法:
回答by Juan Beta
You're better off using parseFloat()
你最好使用 parseFloat()
In situations where you have decimals, like 0.5s for transition-delay, parseInt(x,10) returns zero, where in contrast parseFloat() returns 0.5
在有小数的情况下,例如转换延迟为 0.5s,parseInt(x,10) 返回零,而 parseFloat() 返回 0.5
var x = "0.5s";
var y = parseFloat(x); //returns 0.5