如何在java脚本中从数组中移除值

How can I remove a value from array in java script?

本文关键字:数组 java 脚本      更新时间:2023-09-26

<code>
<!DOCTYPE html>
<html>
	<head>
		<title>Java Script Array methods</title>
		<script type="text/javascript">
		
		var ArrStr = ["Yallappa","Rajesh","Kiran"];
		function LoadArr(){
			document.getElementById("Arr").innerHTML = ArrStr;
		}
		
		function But1Click(){
			
			ArrStr.push(document.getElementById("TxtBox").value);
			document.getElementById("Arr").innerHTML = ArrStr;
		}
		
		function But2Click(){
			var Indx = ArrStr.indexOf(document.getElementById("Arr").value);
			alert(Indx);
			if(indx > -1){
				arrstr.splice(document.getelementbyid("arr").value,1);
			}
			document.getelementbyid("arr").innerhtml = arrstr;
		}
		
		</script>
	</head>
	<body onLoad="LoadArr()">
		<h2 id="Arr"></h2><br>
		<input type="text" id="TxtBox"/><br>
		<input type="button" onclick="But1Click()" text="Push into Array" value="Push into Array"/><br>
		<input type="button" onclick="But2Click()" text="Remove from Array" value="Remove From Array"/>
		
	</body>
</html>
</code>
我想根据按钮点击事件在文本框中添加和删除文本。并在h2标签中显示字符串数组。在这个过程中,我可以在数组中添加一个新字符串,但不能删除字符串。为什么请解释我?

But2Click方法中将arrstr更改为ArrStr,将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
        }