【问题标题】:Using substring length to determine how to splice returning not-a-number使用子串长度确定如何拼接返回非数字
【发布时间】:2015-06-16 11:54:04
【问题描述】:

我使用变量的子字符串来确定如何对字符串进行切片。 字符串本身有四个字符长,并附有一个数字。即“doop0”/“doop1”等。我试图使用字符串长度来确定是否切掉更多。就像字符串变成“doop10”一样,从“10”中切出并解析它。但我得到 NaN 回报,我不知道为什么! 我的代码如下所示:

    var num;
    var numberCount = -1;
    var nameCount = 5;
    socket.on('Balls', function(msg)
    {
        console.log("Minus: "+parseInt(msg.Name.Length) - nameCount);
        if(msg.Name.length == nameCount)
        {
            num = parseInt(msg.Name.slice(numberCount));
        }
        if(msg.Name.Length > nameCount)
        {
            console.log("Minus: "+msg.Name.Length - nameCount);
            numberCount- (msg.Name.Length - nameCount);
            nameCount+ (msg.Name.Length - nameCount);
            num = parseInt(msg.Name.slice(numberCount));
        }

最初的 if 语句将查看 msg 并切掉相关信息。 第二个 if 语句将检查长度是否增加,即“doop9”是否已变为“doop10”或是否已进入 100 个

numberCount- (msg.Name.Length - nameCount); 

会增加断弦量

nameCount+ (msg.Name.Length - nameCount);

将增加名称计数,因此它将在第一个 if 语句中

num = parseInt(msg.Name.slice(numberCount));

获取该实例。 我收到 NaN 错误有什么原因吗?

【问题讨论】:

  • 你能提供一个object的例子吗?默认情况下,字符串的长度属性不大写,因此除非您创建自己的属性,否则这可能是问题所在。
  • 为什么不直接使用正则表达式来获取号码? 'doop10'.replace(/[^0-9.]/g, ''); // 10
  • 我拼错了长度我也用了大写:(

标签: javascript substring string-length


【解决方案1】:

您的一个问题是您正在调用numberCount- (msg.Name.Length - nameCount);,它不会做任何事情,因为它不会就地修改。相反,请尝试在此之后添加=。此外,您正试图从string 中减去integer

console.log( ("Minus: " + parseInt(msg.Name.Length)) - nameCount );

尝试取(例如)"Minus: 4",并从中减去 3"Minus: 4" - 3,这将导致 NaN 错误。

固定代码:

var num;
var numberCount = -1;
var nameCount = 5;
socket.on('Balls', function(msg)
{
    console.log("Minus: "+(parseInt(msg.Name.Length) - nameCount));
    if(msg.Name.length == nameCount)
    {
        num = parseInt(msg.Name.slice(numberCount));
    }
    if(msg.Name.Length > nameCount)
    {
        console.log("Minus: "+(msg.Name.Length - nameCount));
        numberCount-=(msg.Name.Length - nameCount);
        nameCount+=(msg.Name.Length - nameCount);
        num = parseInt(msg.Name.slice(numberCount));
    }

【讨论】:

    【解决方案2】:

    操作顺序。您正在向字符串添加一个数字,而不是尝试从一个字符串中减去一个数字。

    你的代码是这样的:

    console.log( ("Minus: " + parseInt(msg.Name.Length)) - nameCount );
    

    当你需要这个时

    console.log( "Minus: " + (parseInt(msg.Name.Length)) - nameCount) );
    

    您的代码在进行加法/减法时还有其他问题,但不存储值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多