我写了一个Java脚本程序,它必须做以下事情:它必须从表格中的文本中取出句子,然后在表格中按字母顺序查找句子中每个单词的出现次数,如下所示:
this : 5 times
the : 2 times .....and so on
但实际上我的程序执行以下操作,并且在单击搜索按钮时不显示结果,如果我们单独使用函数 button-pressed() ,它的工作方式如下:
this :1
this :2
this:3
this:4
this:5
the:1
the:2....and so on
我想出现没有多余值的最后一个值,所以请帮助这是我的代码:
<script type = "text/javascript"><!--
function buttonPressed() {
var searchForm = document.getElementById( "searchForm" );
var inputVal = document.getElementById( "inputVal" );
var arr =inputVal.split(" ");
var counts = {};
arr.sort();
for(var i = 0; i< arr.length; i++) {
var num = arr[i];
if(counts[num])
counts[num]=counts[num]+1 ;
else
counts[num]=1;
document.writeln("<table border = \"4\">" );
document.writeln( "<caption><h3>Search's Results: <h3/></caption>" );
document.writeln( "<tr><td>"+arr[i]+" :</td><td>" +counts[num] + "</td></tr></tbody></table>" );
}
} // end function buttonPressed
// --></script>
<form id = "searchForm" action = "">
<h1>The string to search is:<br /></h1>
<p>Enter Sentence You Wnt To Find The Occurrence Of Each Word In It :
<input id = "inputVal" type = "text" />
<input name = "search" type = "button" value = "Search" onclick = "buttonPressed()" /><br /></p></form>