JAVASCRIPT帮助 - 代码无效

时间:2015-11-10 23:21:19

标签: javascript

我的代码不起作用,有人可以告诉我这是什么问题吗? 我猜它是for循环,但我找不到问题。

git log --oneline --graph --decorate -n 10

3 个答案:

答案 0 :(得分:0)

您的代码中存在两个问题:

  1. 在for循环中,使用变量的长度来建立停止条件

    for(var i = 0; i< username.length; i ++)

  2. BR未定义

  3. 工作代码:http://jsfiddle.net/f643fr4w/

答案 1 :(得分:-1)

从输出中我可以假设您只想检查username是否至少包含一个数字,实际上是:数字。

// iterate over the input
for (var i = 0; i < username.length; i++) {
  // check if it is a number (not a digit but that's the same here)
  if (isFinite(username.charAt(i))) {
    result = true;
    // The requirement "one or more numbers" is fulfilled,
    // we can break out of the loop
    break;
  } 
  else {
    result = false;
  }
  // print something according to "result"
  if(result === true){
    document.write('The username consists of one or more numbers.');
  } else {
    document.write('The username must consist of one or more numbers.');
  }
}

你必须查看字符串的全长,以确定是否有没有数字,但如果你想知道其中是否有任何数字则不会

现在,如果您想测试它是否包含数字,您必须重新编写要求,现在它们有点过于模糊。

其他提示:

  • 您需要检查输入,总是必须检查用户输入!

  • 您需要知道JavaScript字符串是UTF16。很少有问题,但如果你遍历JavaScript字符串,那么很容易就会出现问题。

  • String.charAt()返回一个字符,而不是数字。不要依赖JavaScript中的自动转换,如果你依赖它,你太容易用脚射击自己,但如果你不依赖它,那么要小心。

  • 请不要使用document.write,使用控制台(如果可用)或更改HTML元素的文本节点。

考虑到这些要点,你可能会得到这样的结论:

// make a list of digits
var digits = ['0','1','2','3','4','5','6','7','8','9'];
// ask the user for a username
var username = prompt("Please enter a your username:");
// check input
if (username.length === 0) {
  console.log('no username given');
} else {
  for (var i = 0; i < username.length; i++) {
    // indexOf searches for the same type, that's why the digits above 
    // are strings with quotes around them
    if (digits.indexOf(username.charAt(i)) >= 0) {
      result = true;
      // The requirement "one or more numbers" is fullfilled,
      // we can break out of the loop
      break;
    } 
    else {
      result = false;
    }
  }
  // print something according to "result"
  if (result === true) {
    console.log('The username consists of one or more numbers.');
  } else {
    console.log('The username must consist of one or more numbers.');
  }
}

上面是很多的一个变种,很容易引起一些论坛的激烈讨论(不是在这里!当然不是!;-))但我希望它有所帮助。

答案 2 :(得分:-1)

使用正则表达式来处理这样的恶作剧:

var username = prompt("username plz kk thx");
var result = /[0-9]/.test(username);
document.write("The username " + (result ? "consists" : "must consist") + " of one or more numbers");