简体   繁体   English

为什么我在这里变得不确定?

[英]Why do I get undefined here?

function myFunc() {
    var word = document.getElementById("Text1").value;
    var num = parseInt(document.getElementById("Text2").value);
    var numstr = num.split(",");
    var wordstr = word.split("");
    for (i = 0; i < word.length; i++) {
    }
    document.getElementById("myDiv").innerHTML += (wordstr[(numstr[i])-1]);

}

did I parseInt incorrectly? 我解析不正确吗? I've tried toString(), with ParseInt it doesn't do anything and without it I get 'undefined' 我尝试过toString(),使用ParseInt不会执行任何操作,没有它我会得到“未定义”

The parseInt() function parses a string and returns an integer. parseInt()函数解析一个字符串并返回一个整数。 You check your input with id "Text2" and show your HTML here to clearify the issue. 您检查ID为"Text2"输入,并在此处显示HTML以解决此问题。

Without knowing more about your problem, it looks like you are misunderstanding how parseInt() works. 在不了解您的问题的情况下,您似乎误解了parseInt()的工作方式。 Despite the misleading name, it will read your string character by character, attempting to create an integer. 尽管名称具有误导性,但它会逐字符读取您的字符串,并尝试创建一个整数。 It will stop as soon as it finds a character that can't be part of an integer. 一旦找到不能为整数的字符,它将立即停止。

If you pass it "1,2,3,4" then it will read the 2 fine, but as a comma cannot be parsed as part of an integer, it will return the number 2. It doesn't make sense to call split on a number. 如果将其传递为“ 1、2、3、4”,则它将读取2的整数,但由于逗号无法解析为整数的一部分,因此它将返回数字 2。调用split没有意义。在一个数字上。

As others have said, you really need to give us more details for us to be able to help, but I suspect a large part of the problem is not understanding what some of these functions do. 正如其他人所说,您确实需要向我们提供更多详细信息,以便我们能够提供帮助,但是我怀疑问题的很大一部分是不了解其中某些功能的作用。

Maybe you could explain what you're trying to achieve, then we can help you get there. 也许您可以解释您要达到的目标,然后我们可以帮助您实现目标。 Right now, your code isn't clear enough without extra information. 目前,没有额外的信息,您的代码还不够清楚。

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

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