![](/img/trans.png)
[英]How can I Check if a sentence contains different word of same letter in Java Script?
[英]how i can find the number of occurrence of word in an sentence in java script
我編寫了一個必須執行以下操作的java腳本程序:它必須從表單中的文本中取出句子,然后在表格中按字母順序查找句子中每個單詞的出現次數,如下所示:
this : 5 times
the : 2 times .....and so on
但實際上我的程序執行以下操作,並且在單擊搜索按鈕時不顯示結果,如果我們按下按鈕功能按鈕(),它將按以下方式工作:
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>
你也可以用這個:
"mijn naam is niels, niels is mijn naam".split("niels").length - 1
// Will return 2
哪個會分開,你會有匹配的數量
您在計算過程中嘗試輸出的主要問題是, document.writeln
語句在for循環中
你需要將它們移出:
for(var i = 0; i< arr.length; i++) {
var num = arr[i];
counts[num] = (counts[num] ? counts[num] : 0) + 1 ;
}
document.writeln("<table border=\"4\">");
document.writeln("<caption><h3>Search's Results: <h3/></caption>");
for (var i in counts) {
document.writeln("<tr><td>"+i+" :</td><td>"+counts[i]+"</td></tr>");
}
document.writeln("</tbody></table>");
注意:請閱讀有關htmlencode和document.writeln函數的信息,當你寫入文檔的末尾時,你輸錯了輸出,因為你的特定任務沒問題,但通常你需要輸出到頁面上的特定位置,為此你需要分配一些div的innerHTML
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.