jQuery Declare Array With Custom Values Examples
Have you been wanting to know how to declare an array with values using jQuery? In this article, I am going to show how you can easily declare an array and assign custom values to the array. And once we do that, we will also get array values using jQuery, just to make sure that our assignment is correct. Read on find out more.
Examples to Declare array with values using jQuery
It’s very easy to declare an array with custom values using jQuery. You can use jQuery to declare array and assign values to the array with just 1 line of code. Here is an example that shows you how to do this. The example assumes that we have declared an array of “fruits” and once we click on a button, each of the values of the array are alerted back to us with the key and the corresponding values, so that we can make sure that our array declaration and values assignment is correct.
Example: Here is the complete source to declare array with values using jQuery
<html>
<head>
<title>jQuery Declare Array with values using Example</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>
<body>
<input type="submit" name="btn_alert" id="btn_alert" value="Alert array values / keys" />
<script type="text/javascript">
$(document).ready(function() {
//Declare an array
var fruits_array = ['mango', 'apple', 'grapes'];
$('#btn_alert').click(function(){
$.each(fruits_array, function(key, value) {
alert('Array Key is: '+ key + ' \n Array Key value is: ' + value);
});
return false;
});
});
</script>
</body>
</html>When you run the above code, simply click on the button. You will see that each of the values of the fruits array are being alerted back, along with all their respective keys.
Easy, huh?
Do you know of any other ways to use jQuery to declare array? Feel free to suggest by commenting below.