在javascript中将字符串拆分为2个变量
我想把一个字符串转换成两个变量 我已经创建了一个变量,我正在使用substring来拆分它,但是我似乎无法让它工作 如果我创建了一条警报消息,它显示的是我想要拆分的原始变量(因此我知道那里有一些东西) 我的代码如下所示:在javascript中将字符串拆分为2个变量,javascript,variables,substring,Javascript,Variables,Substring,我想把一个字符串转换成两个变量 我已经创建了一个变量,我正在使用substring来拆分它,但是我似乎无法让它工作 如果我创建了一条警报消息,它显示的是我想要拆分的原始变量(因此我知道那里有一些东西) 我的代码如下所示: // variable 'ca' is set from a XML Element Response alert(ca); // displays a string (eg. 123456789) - which does display fine alert(ca.subs
// variable 'ca' is set from a XML Element Response
alert(ca); // displays a string (eg. 123456789) - which does display fine
alert(ca.substring(0,1)); // should alert 1 but it stops and nothing is displayed
但我添加了ca=“123456789”如下所示,它可以工作
ca = "123456789";
alert(ca); // displays a string (eg. 123456789) - which does display fine
alert(ca.substring(0,1)); // should alert 1 but it stops and nothing is displayed
但是,变量ca设置了一些内容,并在使用子字符串之前显示
有人知道我可能做错了什么吗?您的变量不包含字符串,它包含其他内容,可能是数字 将值转换为字符串,以便能够对其使用字符串方法:
ca = ca.toString();
您的变量不包含字符串,它包含其他内容,可能是数字 将值转换为字符串,以便能够对其使用字符串方法:
ca = ca.toString();
我猜,
ca
不包含字符串,而是一个数字。
当您将变量强制转换为字符串时,它是否起作用
alert(String(ca).substring(0,1));
(请注意,您可以使用typeof
运算符检查变量包含的内容:
console.log(typeof ca);
// number
console.log(typeof String(ca));
// string
更新:ca.toString()和
String(ca)
都应该可以工作,但我个人更喜欢String(ca)
,因为如果ca是null
或未定义的我猜ca
不包含字符串,而是包含数字。
当您将变量强制转换为字符串时,它是否起作用
alert(String(ca).substring(0,1));
(请注意,您可以使用typeof
运算符检查变量包含的内容:
console.log(typeof ca);
// number
console.log(typeof String(ca));
// string
更新:ca.toString()
和String(ca)
都应该可以工作,但我个人更喜欢String(ca)
因为如果ca为null
或未定义
也可以,如果我不得不猜测,在ajax调用仍在运行时,您可能正在查找ca
值……您可以发布相关代码吗?您的xml响应可能在开头有一些空格。请尝试-警报('>'+ca.substring(0,1)+'请告诉我您已经检查了页面上的错误…如果我不得不猜测,您可能在ajax调用仍在运行时正在查找ca
值…您可以发布相关代码吗?您的xml响应可能在开始时有一些空格。请尝试-alert('>>')+ca.substring(0,1)+'请告诉我,你已经检查了页面上的错误…你的位置是一个数字,我需要将其转换为字符串。-你的位置是一个救生圈。你的位置是一个数字,我需要将其转换为字符串。-你的位置是一个救生圈。