为什么str.substr(0,4)不是一个函数? [英] Why str.substr(0,4) is not a function?

查看:294
本文介绍了为什么str.substr(0,4)不是一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery编写脚本,并且得到了以下数字7.2387.我所拥有的只是获得7.23,为此,我编写了以下代码:

I'm making a script with jQuery and I got the following number 7.2387. All i have is get only 7.23, for this i've written the following code:

var str = 7.2387;
var shorter = str.substr(0,4);

但是我收到此错误:

all.js?55:92 Uncaught TypeError: str.substr is not a function
    at HTMLSpanElement.<anonymous> (all.js?55:92)
    at HTMLSpanElement.dispatch (jquery.min.js:2)
    at HTMLSpanElement.y.handle (jquery.min.js:2)

并且我的整个脚本停止运行,仅当我删除substr(x,y)函数时,该脚本才起作用.我确保有更新的jQuery.怎么了?

And my whole script stops working, it works only when I remove the substr(x,y) function. I made sure to have jquery updated. What's wrong?

推荐答案

因为str不是字符串,并且没有substr方法.您必须先将其转换为字符串.

Because str is not a string and doesn't have a substr method. You have to convert it to a string first.

var str = 7.2387;
var shorter = String(str).substr(0, 4);
console.log(shorter);

这篇关于为什么str.substr(0,4)不是一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆