此“计数器”的目标是查看“ ToCount”字符串中有多少个不同的单词。为此,它使ToCount成为数组,然后遍历元素,检查它们是否已经存在,如果不存在,则将它们添加到那里。
在循环后,ToCountArr2保持为空,并且显示长度为0。为什么会发生这种情况,我该怎么办?
我运行了一个调试器,发现没有元素添加到第二个列表中,好像如果第一个数组的第i个元素已经在第二个数组中,则“ if”控件中没有任何内容。
function counter(){
var ToCount = document.getElementById("demo").value; //the contents of a textbox
var ToCountArr1 = ToCount.split(" ");
var ToCountArr2 = new Array;
var i = 0;
var lengthToCountArr1 = ToCountArr1.length;
var wordToPush;
while (i < lengthToCountArr1){
if(ToCountArr2.includes(ToCountArr1[i] === false)) {
wordToPush = ToCountArr1[i];
ToCountArr2.push(wordToPush);
}
i = i + 1;
}
alert(ToCountArr2.length);
}
答案 0 :(得分:1)
问题在于此行if(ToCountArr2.includes(ToCountArr1[i] === false))
。在这里,花括号必须位于ToCountArr1[i]
之后,ToCountArr1[i] === false)
这行正在检查ToCountArr1
中的值是true还是false。
此行
if(ToCountArr2.includes(ToCountArr1[i] === false))
将被评估为
if(ToCountArr2.includes(true/false))
取决于ToCountArr1[i] === false)
function counter() {
var ToCount = document.getElementById("demo").value; //the contents of a textbox
var ToCountArr1 = ToCount.split(" ");
var ToCountArr2 = new Array;
var i = 0;
var lengthToCountArr1 = ToCountArr1.length;
var wordToPush;
while (i < lengthToCountArr1) {
if (ToCountArr2.includes(ToCountArr1[i]) === false) {
wordToPush = ToCountArr1[i];
ToCountArr2.push(wordToPush);
}
i = i + 1;
}
console.log(ToCountArr2.length);
}
counter()
<input type='text' id='demo' value='Test Values'>
您可以通过将
替换为if (ToCountArr2.includes(ToCountArr1[i]) === false) {
来使其最小化
if (!ToCountArr2.includes(ToCountArr1[i])) {
答案 1 :(得分:1)
您的wordcount
函数应使用一个参数,以便您可以传递一个字符串。这意味着您可以在任意字符串上使用wordcount
函数,而不仅仅是“演示”元素。另外,这是学习Map-
const wordcount = (str = "") =>
{ const result =
new Map
for (const s of str.split(/ /))
if (s === "")
continue
else if (result.has(s))
result.set(s, result.get(s) + 1)
else
result.set(s, 1)
return Array.from(result.entries())
}
const prettyPrint = (value) =>
console.log(JSON.stringify(value))
<!-- pass this.value as the string for wordcount
-- wordcount returns a value that we could use elsewhere
-- prettyPrint displays the value to the console
-->
<input onkeyup="prettyPrint(wordcount(this.value))">
运行代码段并将以下行复制/粘贴到字段中-
this is the captain speaking. is this the commander?
您将看到此输出-
[["this",2],["is",2],["the",2],["captain",1],["speaking.",1],["commander?",1]]
答案 2 :(得分:0)
这是一个有效的示例。我认为这会帮助您正确的方法。在这里,我使用indexOf来检查数组中是否存在该值。
function counter(){
var ToCount = "I am string just for text.";//document.getElementById("demo").value; //the contents of a textbox
var ToCountArr1 = ToCount.split(" ");
var ToCountArr2 = new Array;
var i = 0;
var lengthToCountArr1 = ToCountArr1.length;
var wordToPush;
while (i < lengthToCountArr1){
if( ToCountArr2.indexOf(ToCountArr1[i]) == -1 ) {
wordToPush = ToCountArr1[i];
ToCountArr2.push(wordToPush);
}
i = i + 1;
}
alert(ToCountArr2.length);
}
counter();