如何创建一个接受输入的函数并测试它是否是回文
How to to create a function that will take an input and test if it's a palindrome or not?
这是我现在写的函数。Web 控制台对我没有多大作用。每次在文本框中输入单词时,即使它是回文,也只是返回"undefinedThis is not a palindrome!"
。
不知道这里出了什么问题。也许与if
声明有关?如何使函数忽略大写字母?我希望它既考虑"bob"
,又"Bob"
回文。
function test() {
// Assumes: a string is entered into the "palin" text box
// Results: tests if the string is a palindrome and
// returns the conclusion to outputDiv
var word, copy, i;
word = document.getElementById("palin").value;
copy = " ";
i = 0;
while (i < word.length) {
copy = word.charAt(i) + copy;
i=i+1;
}
if (word === copy) {
document.getElementById("outputDiv").innerHTML =
document.getElementById("outputDiv").value +
"This is a palindrome!";
} else {
document.getElementById('outputDiv').innerHTML =
document.getElementById('outputDiv').value +
"This is not a palindrome!";
}
}
最好将逻辑与演示文稿分开。在您的情况下,逻辑是回文检查。演示文稿正在从文本框获取输入并将输出发送到div。
这就是我要做的:
var input = document.getElementById("input");
var output = document.getElementById("output");
document.getElementById("button").addEventListener("click", function () {
var s = input.value;
output.innerHTML = s + " is" + (isPalindrome(s) ? "" : " not")
+ " a palindrome.";
});
function isPalindrome(s) {
s = s.toLowerCase();
return s.split("").reverse().join("") === s;
}
<input type="text" id="input"/>
<button id="button">Palindrome?</button>
<div id="output"></div>
如您所见,我已将isPalindrome
逻辑放入一个单独的函数中。因此,我将逻辑与演示文稿分开。您应该始终这样做。它使编程变得更加简单。
你的代码几乎是正确的,这是固定的JSFIDDLE示例
将您的代码更改为
function test() {
var word, copy, i;
word = document.getElementById("palin").value.toLowerCase();//turn to lowercase
copy = "";
i = 0;
while (i < word.length) {
copy = word.charAt(i) + copy;
i=i+1;
}
if (word === copy) {
document.getElementById("outputDiv").innerHTML =
document.getElementById("palin").value + " This is a palindrome!";
} else {
document.getElementById('outputDiv').innerHTML =
document.getElementById('palin').value + " This is not a palindrome!";
}
}
copy = " ";
应该更改为copy = "";
这是第一个问题,因为"bob" not equal to "bob "
你使用了未定义document.getElementById("outputDiv").value
,因为它是一个div而不是文本区域,所以值是未定义的,你可能需要的是document.getElementById("palin").value
相关文章:
- 为函数代码编写测试
- AngularJS指令单元测试中未定义的函数
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- 为什么不是'我的函数在解析云代码中工作吗?当我在Angular和Express中测试时,它是有效的
- 测试抛出异常的函数
- 如何使用console.log语句在Mocha中测试函数
- 是否可以测试javascript函数是否是构造函数
- 如何在JavaScript中对箭头函数进行单元测试
- Mocha/Chai测试链接到函数返回断言错误
- 如何在Javascript中测试函数的相等性
- jQuery-有没有一种方法可以测试函数是否异步
- 如何按照承诺使用mocha/chai/chai测试ES7异步函数
- 在http服务单元测试中使用request-js时,chai.request不是一个函数
- Jasmine:测试setTimeout函数会抛出一个错误
- Mocking console.log()/MOCHA测试框架中的任何其他函数
- 如何使用console.log在因果报应测试中检查函数
- 使用 for 循环中的函数测试字符串时,我一直陷入无限循环
- 如何使用一个函数测试Angular控制器,该函数可以在不嘲笑AJAX调用的情况下进行AJAX调用
- 函数测试一系列值中的值和返回值
- 是否有任何QUnit断言/函数测试数组中的元素