2016-09-11 6 views
-2

Javaスクリプトの配列から値を削除するにはどうすればよいですか?

<code> 
 
<!DOCTYPE html> 
 
<html> 
 
\t <head> 
 
\t \t <title>Java Script Array methods</title> 
 
\t \t <script type="text/javascript"> 
 
\t \t 
 
\t \t var ArrStr = ["Yallappa","Rajesh","Kiran"]; 
 
\t \t function LoadArr(){ 
 
\t \t \t document.getElementById("Arr").innerHTML = ArrStr; 
 
\t \t } 
 
\t \t 
 
\t \t function But1Click(){ 
 
\t \t \t 
 
\t \t \t ArrStr.push(document.getElementById("TxtBox").value); 
 
\t \t \t document.getElementById("Arr").innerHTML = ArrStr; 
 
\t \t } 
 
\t \t 
 
\t \t function But2Click(){ 
 
\t \t \t var Indx = ArrStr.indexOf(document.getElementById("Arr").value); 
 
\t \t \t alert(Indx); 
 
\t \t \t if(indx > -1){ 
 
\t \t \t \t arrstr.splice(document.getelementbyid("arr").value,1); 
 
\t \t \t } 
 
\t \t \t document.getelementbyid("arr").innerhtml = arrstr; 
 
\t \t } 
 
\t \t 
 
\t \t </script> 
 
\t </head> 
 
\t <body onLoad="LoadArr()"> 
 
\t \t <h2 id="Arr"></h2><br> 
 
\t \t <input type="text" id="TxtBox"/><br> 
 
\t \t <input type="button" onclick="But1Click()" text="Push into Array" value="Push into Array"/><br> 
 
\t \t <input type="button" onclick="But2Click()" text="Remove from Array" value="Remove From Array"/> 
 
\t \t 
 
\t </body> 
 
</html> 
 
</code>
私は追加して、ボタンのクリックイベントに基づいてテキストボックスからテキストを削除したかったです。文字列の配列をh2タグに表示します。 これで、配列に新しい文字列を追加することはできますが、文字列を削除することはできません。 なぜ私を説明してください?

ArrStrから But2Click方法変更 arrstr
+1

JSでは大文字と小文字が区別されます。あなたのBut2click()関数では、代入文に "Indx"を、if()文に "indx"を使用しました – jophab

+0

大文字小文字のエラーがあります – Li357

答えて

0

indx IndxへのあなたのBut2Clickはエラーに満ちています。次のようになります。

function But2Click(){ 
      var Indx = ArrStr.indexOf(document.getElementById("TxtBox").value); //id here should be of textbox 
      alert(Indx); 
      if(Indx > -1)//case of variable was incorrect 
      { 
       ArrStr.splice(Indx,1); //splice function needs index as first argument 
      } 
      document.getElementById("Arr").innerHTML = ArrStr;//id was incorrect and case in variable name was incorrect 
     } 
+0

ありがとう、私はそれらを修正しました。文字列を削除します。アラートのたびにインデックスが-1として表示されます。 –

+0

@ YallappaBestha私が見落としていたコードには多くのエラーがありました。私の修正された答えをチェックしてください –

関連する問題