Hello friends, In this tutorial, I am providing a working example that shows you, how to add and remove the value in the javascript array. To implement this example I am using a simple javascript code that will be easily understandable to you. I hope this helps you lot while working on Javascript and Javascript array.
After completing this unit, you’ll able to,
- Add and Remove value in Array using Javascript.
So let’s get started,
Add value in Array
var myArray=[];
function add(){
myArray.push(yourValue);
}
Remove value from Array
var myArray=[];
function remove(){
var index = myArray.indexOf(yourValue);
if (index > -1) {
myArray.splice(index, 1);
}
}
Example: I am providing a complete code example using HTML page that let you know how this works for you.
<html>
<head>
<title>Add and Remove value in Array in Javascript</title>
</head>
<body>
<input type="button" value="Add" onclick="add();"/>
<input type="button" value="Remove" onclick="remove();"/>
<br/>
<div id="divValue">
</div>
<script>
var i=0;
var myArray=[];
function add(){
i++;
myArray.push(i);
document.getElementById("divValue").innerHTML=myArray;
}
function remove(){
var index = myArray.indexOf(i);
if (index > -1) {
myArray.splice(index, 1);
}
document.getElementById("divValue").innerHTML=myArray;
i--;
}
</script>
</body>
</html>
Output:- Get selected value in dropdown list using JavaScript
- Check all Checkboxes in Page via Browser Console
Conclusion:
Hope you like this tutorial, for any query or suggestions please feel free to comment.
Thank you.
0 Comments
Post a Comment