Javascript Data Type How to - Push to first free place in an Array








Question

We would like to know how to push to first free place in an Array.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- ww  w  .  j a  v a  2 s. c  o m-->
function push(arr, to_be_added) {
    for (var i in arr) {
        if (arr[i] == null || arr[i].length == 0 || arr[i] == undefined) {
            arr[i] = to_be_added;
            return;
        }
    }
}
var arr = [1,2,3,undefined,,null];
push(arr, 4);
document.writeln(arr);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: