i want write simple example, count messages. very important: need check if array null or not using index, (main_arr[0]):
<body> <input type="button" id="btn1" name="click" value="click"/> <script type="text/javascript"> $(document).ready(function () { var main_arr ; $("#btn1").click(function () { if (main_arr[0] == null) { main_arr = []; alert("array initialized!"); } else { main_arr.push("message"); alert("in array " + main_arr.length + " messages!"); } }); }); </script> </body> how check if main_arr[0] have value?
try
is 'main_arr' defined?
if (typeof main_arr != "undefined") { } does 'main_arr' has elements?
if (main_arr.length > 0) { } so code becomes
$(document).ready(function () { var main_arr; $("#btn1").click(function () { if (typeof main_arr == 'undefined') { main_arr = []; } if (main_arr.length > 0) { // has elements. time check '0th' element } else { // no elements. push one. main_arr.push('message'); } }); }); hope helped.
Comments
Post a Comment