1

次のことを行う必要がある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>
4

2 に答える 2

2

これを使用することもできます:

"mijn naam is niels, niels is mijn naam".split("niels").length - 1
// Will return 2

どちらが単語で分割され、一致の数が得られます

于 2013-10-23T18:04:26.373 に答える