[英]JSON.parse convert string to array error
So I am trying to write this function that calculates the average based on values in a string by first converting it to an array with JSON.parse. 因此,我尝试编写此函数,该函数通过首先将其转换为带有JSON.parse的数组来基于字符串中的值计算平均值。 I am getting an error on the JSON.parse and I am not sure why. 我在JSON.parse上遇到错误,我不确定为什么。
"Uncaught SyntaxError: Unexpected token N" line: var elmt = JSON.parse('[' + string + ']'); “未捕获的SyntaxError:意外的令牌N”行:var elmt = JSON.parse('['+ string +']');
function averageRisk() {
var sum = 0;
var string = +health_grab;
// this returns a string from my database like this: 8,5,3,5,2,6,8,9
var elmt = JSON.parse('[' + string + ']');
console.log("healthLevels: " + elmt);
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10);
}
if (isNaN(sum)) {
return false;
}
avg = Math.round(sum / elmt.length);
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
You have a unary plus +
operator on +health_grab
. 您在+health_grab
上具有一元加号 +
。 This attempts to convert it into a number. 这将尝试将其转换为数字。 This doesn't work and it produces NaN . 这是行不通的,它会产生NaN 。
JSON.parse()
tries and fails to parse NaN
resulting in the error when it reaches the first character N
. JSON.parse()
尝试解析NaN
并将失败,并在解析到第一个字符N
时导致错误。
Uncaught SyntaxError: Unexpected token N 未捕获到的SyntaxError:意外令牌N
Remove the +
and it should fix the error. 删除+
,它应该可以修复错误。
I think you have a typo on your third line. 我认为您的第三行有错字。 You have an extra "+". 您有一个额外的“ +”。 When I test this in Node.JS I get the same error as you. 当我在Node.JS中对此进行测试时,我得到与您相同的错误。 Remove the "+" and it should work. 删除“ +”,它应该可以工作。
If this isn't a typo, what were you attempting to achieve with the prefixed "+"? 如果这不是拼写错误,那么您尝试使用前缀“ +”实现什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.