JavaScript中的问题 [英] Problem in JavaScript
问题描述
我有一些javascript行如下:
I have some lines of javascript as below:
var start = str.split("-")[0];
var end = str.split("-")[1];
alert(start + " " + end);
for(strt=start;strt<=end;strt++)
{
alert(strt);
}
现在,如果我给str小于10的值,即1-9,7-9 >
或大于等于10,即10-12,10-15,11-40它工作正常..但如果我在范围之间包括10,即6-12,8-12,9-11等它不起作用..我无法弄清楚..仍在尝试调试...有人请和我一起调试这个!
我通过将8-12这样的情况分解为8-9和10-12等待处理的部分来解决问题,但是如果可以直接处理则更好。
Now, If i give value for str less than 10 i.e. 1-9, 7-9
or greater than equal to 10 i.e. 10-12, 10-15, 11-40 It works fine.. but of if I include 10 in between range i.e. 6-12, 8-12, 9-11 etc. It doesn't work.. I am unable to figure out.. still trying to debug... will anyone please join me to debug this out!
I fount the solution by breaking a case like 8-12 into parts to be processed like 8-9 and 10-12, but it'd be better if direct processing could be done.
推荐答案
您正在比较字符串值而不是数字。由于字符'6'
大于字符'1'
,因此您的循环将永远不会执行。
在处理之前将值转换为数字:
You're comparing string values instead of numbers. Since the character'6'
is greater than the character'1'
, your loop will never execute.
Convert the values to numbers before processing them:
var str = "6-10";
var parts = str.split("-");
var start = parseInt(parts[0]);
var end = parseInt(parts[1]);
alert(start + "-" + end);
for (var strt = start; strt <= end; strt++)
{
alert(strt);
}
http:// jsfiddle .net / YrGHx / [ ^ ]
这篇关于JavaScript中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!