I am trying to run a script where I want a part to run if i exists (meaning that there is a value of i, any value) or another part to run if there is no value for i, can anyone enlight me?
I am talking about the for loop, something like
for (var i=0; i<data.length; i++) {
if (var i == doesnt exist) {
code1 runs
}
else {
code2 runs
}
}
Heres the code in the HTML
<script>
function funfacts(o){
var facts = document.getElementById('funfacts');
var data = o.query.results.a;
for(var i=0;i<data.length;i++){
var out = document.createElement('a');
facts.appendChild(out);
out.href = data[i].href;
out.innerHTML = data[i].alt;
out.appendChild(document.createElement('br'));
}
}
</script>
This assumes that you are iterating though an array and some of the objects in that array are
null. Otherwise, this loop will never run past the last array index, so there is no need to safe guard it unless you actually havenullin the array.Note that this also will fail on a zero, since a zero is considered as false in javascript. If this is a problem in your case, you can compare it with
nullAnd outside a loop you can check to see if an array has a value at an index at all via:
This will see if there is a value at that index, could be false, zero, null or anything else and this test would pass.
But again, inside that loop it’s guaranteed to be within the array bounds.