Javascript Number.prototype.function不处理jQuery(..).val()的结果

Javascript Number.prototype.function不处理jQuery(..).val()的结果,javascript,jquery,numbers,prototype,Javascript,Jquery,Numbers,Prototype,我从另一个代码中获取了这段代码 基本上,它返回给定数字的小数位数。问题是我需要从输入中的数字中获取该值: console.log($('#myinput').val().countDecimals()); …但该操作返回:未捕获类型错误:未定义不是函数 如何集成前面的代码以使用输入值(使用jQuery)?谢谢 这是因为.val()实际上返回一个对象:object[value]。只需在上面执行parseFloat: console.log( parseFloat( $('#myinput').v

我从另一个代码中获取了这段代码

基本上,它返回给定数字的小数位数。问题是我需要从输入中的数字中获取该值:

console.log($('#myinput').val().countDecimals());
…但该操作返回:未捕获类型错误:未定义不是函数

如何集成前面的代码以使用输入值(使用jQuery)?谢谢

这是因为
.val()
实际上返回一个对象:
object[value]
。只需在上面执行
parseFloat

console.log( parseFloat( $('#myinput').val() ).countDecimals() );

它将给出期望的结果

 <html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type ="text" id="inpVal">
<input type ="button" id="inpBtn" value="click!!!!">
<script>
Number.prototype.countDecimals = function () {
    if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
    return this.toString().split(".")[1].length || 0; 
}

$("#inpBtn").click(function(){
    var x = parseFloat($("#inpVal").val()).countDecimals();
    alert(x);
});
</script>
</body>
</html>

Number.prototype.countDecimals=函数(){
if(Math.floor(this.valueOf())==this.valueOf())返回0;
返回此.toString().split(“.”[1]。长度| | 0;
}
$(“#inpBtn”)。单击(函数(){
var x=parseFloat($(“#inpVal”).val()).countDecimals();
警报(x);
});

您正在
Number
对象的原型中定义
countDecimals
函数,因此它只能在
Number
类型的对象上调用。我还没有测试过这个,但是你可以使用
Number($('.\myinput').val()).countDecimals()

是的,但是如果我尝试执行
$('.\myinput').val().countDecimals()
,它就是不起作用的。我的错了,我的问题出错了。已更正。实际引发此错误的:TypeError:无法读取的属性“length”undefined@andufo您是否定义了
?这里有一个例子:完美!它实际上起作用了,我在测试你的解决方案时出错了。谢谢使用Number和parseFloat有什么区别?(两者都很好)
countDecimals
可以处理任何数字或数值;JavaScript根据需要将基元类型升级为相应的对象类型。(这就是为什么
1.23.toFixed(1)
可以工作的原因。)@andufo
parseFloat()
将其转换为浮点数
Number()
将其转换为一个数字。总的来说,两者都是一个数字。
 <html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type ="text" id="inpVal">
<input type ="button" id="inpBtn" value="click!!!!">
<script>
Number.prototype.countDecimals = function () {
    if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
    return this.toString().split(".")[1].length || 0; 
}

$("#inpBtn").click(function(){
    var x = parseFloat($("#inpVal").val()).countDecimals();
    alert(x);
});
</script>
</body>
</html>