[英]Why Runtime error if input array element are parsed to integer altogether in javascript?
I was working on counting sort1 problem on hackerrank. 我正在计算hackerrank上的sort1问题。 I am using JavaScript to solve the problem.
我正在使用JavaScript来解决问题。
Standard input is providing a number and an array which I was reading like this 标准输入提供了我正在这样读取的数字和数组
var inp = input.split('\n')
var n = parseInt(inp[0]); //Number of elements
var ar = inp[1].split(' ').map(function(item){
return parseInt(item);
}); //Array of numbers.
I was using above code in almost all of my solutions, it always worked. 我几乎在我的所有解决方案中都使用了上面的代码,它始终有效。 Then I process the above array
ar
in for
loop which is giving runtime error in one of the test cases(last testcase). 然后,我在
for
循环中处理上述数组ar
,这在一个测试用例(最后一个测试用例)中给出了运行时错误。
for(var i = 0; i < n; i++) {
var number = ar[i];
//more code
}
But if I don't parse elements of the array using map function but parse them later in for loop, one by one, I don't get any error. 但是,如果我不使用map函数解析数组的元素,而是稍后在for循环中逐一解析它们,那么我不会收到任何错误。
var ar = in[1].split(' '); //Array of numbers in string format
for(var i = 0; i < n; i++) {
var number = parseInt(ar[i]);
//more code
}
Can Anyone explain Why? 谁能解释为什么?
in
is a keyword, and you are trying to use it as a variable. in
是一个关键字,您正在尝试将其用作变量。 I'm not sure why it says "Runtime Error", since this is actually a parsing error. 我不确定为什么会显示“运行时错误”,因为这实际上是解析错误。 Once renamed to something else, I could run the first two paragraphs error-free.
一旦重命名为其他名称,我就可以无错误地运行前两段。
The only problem I remember having on Hackerrank that the .split()
method often gave an empty string ( ""
) as the last element of the array. 我记得在Hackerrank上遇到的唯一问题是
.split()
方法通常将空字符串( ""
)作为数组的最后一个元素。 Probably that's why you failed on the last test case. 也许这就是为什么您在最后一个测试用例上失败了。
Make your logic like: 使您的逻辑像:
if(arr[i] !== "")
// perform operations
else
break;
Also, you can't use in
as a identifier because it is a reserved keyword. 另外,您不能将
in
用作标识符,因为它是保留关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.