简体   繁体   English

Node.JS / Javascript - 将字符串转换为整数,在我不期望它时返回NaN

[英]Node.JS/Javascript - casting string to integer is returning NaN when I wouldn't expect it to

This is all in the context of a larger program, so Im going to try keep it simple, showing the offending lines only. 这都是在一个更大的程序的背景下,所以我将尝试保持简单,只显示有问题的行。 I have an array of values that are numbers in string form a la "84", "32", etc. 我有一个数组值,字符串形式的数字为“84”,“32”等。

Yet THIS line 然而这条线

console.log(unsolved.length + " " + unsolved[0] + " " + parseInt(unsolved[0]) + " " + parseInt("84"));

prints: 打印:

4 "84" NaN 84

"84" is the array element Im trying to parseInt! “84”是我试图解析的数组元素! Yet it won't work unless I take it out of the context of an array and have it explicitly written. 然而,除非我把它从数组的上下文中删除并明确地写出来,否则它将无法工作。 What's going on? 这是怎么回事?

You can try removing the quotations from the string to be processed using this function: 您可以尝试使用此函数从要处理的字符串中删除引号:

function stripAlphaChars(source) { 
  var out = source.replace(/[^0-9]/g, ''); 

  return out; 
}

Also you should explicitly specify that you want to parse a base 10 number: 您还应明确指定要解析基数为10的数字:

parseInt(unsolved[0], 10);

parseInt would take everything from the start of its argument that looks like a number, and disregard the rest. parseInt将从其参数的开头看起来像一个数字,并忽略其余的一切。 In your case, the argument you're calling it with starts with " , so nothing looks like a number, and it tries to cast an empty string, which is really not a number. 在你的情况下,你调用它的参数以" ,所以没有看起来像一个数字,并且它试图转换一个空字符串,这实际上不是一个数字。

You should make sure that the array element is indeed a string which is possible to parse to a number. 您应该确保数组元素确实是一个可以解析为数字的字符串。 Your array element doesn't contain the value '84' , but actually the value '"84"' (a string containing a number encapsulated by ") 您的数组元素不包含值'84' ,但实际上值'"84"' (包含由“封装”的数字的字符串)

You'll want to remove the " from your array elements, possible like this: 你想要删除"你的数组元素,可能这样:

function removeQuotationMarks(string) {
  return (typeof string === 'string') ? string.replace(/"|'/g, '') : string;
}

unsolved = unsolved.map(removeQuotationMarks);

Now all the array elements should be ready to be parsed with parseInt(unsolved[x], 10) 现在所有的数组元素都准备parseInt(unsolved[x], 10)解析parseInt(unsolved[x], 10)

First we need to replace " to ' in give data using Regex and replace and then we need to cast. 首先,我们需要使用Regex替换“to”来替换数据然后我们需要进行转换。

 var i = 1; var j = "22" function stringToNumber(n) { return (typeof n === 'string') ? parseInt(Number(n.replace(/"|'/g, ''))) : n; } console.log(stringToNumber(i)); // 1 console.log(stringToNumber(j)); // 22 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM