Um recurso que seria útil em JavaScript:
<br> for
… else
declarações:
// Loop through an array of people:
for (var i = 0, l = people.length; i < l; i++) console.log(people[i]);
// If we didn't enter the previous loop:
else console.log('No people! :(');
<br>
e while
… else
declarações:
// Loop through an array of people:
var numPeople = people.length;
while (numPeople--) console.log(people[numPeople]);
// If we didn't enter the previous loop:
else console.log('No people! :(');
<br>
Aqui está outro exemplo de uso (com for
… else
):
function removeKeys(object /*, keyStr1, keyStr2, etc.*/) {
var args = arguments,
hasOwnKey = {}.hasOwnProperty.call,
key;
// Loop through arguments last first not including the first argument:
for (var numArgs = args.length; --numArgs;) {
key = args[numArgs];
delete object[key];
}
// If there was only one argument (the previous loop didn't execute):
else for (key in object) {
if (hasOwnKey(object, key)) delete object[key];
}
};
<br>
e novamente com while
… else
:
function removeKeys(object /*, keyStr1, keyStr2, etc.*/) {
var args = arguments,
numArgs = args.length,
hasOwnKey = {}.hasOwnProperty.call,
key;
// Loop through arguments last first not including the first argument:
while (--numArgs) {
key = args[numArgs];
delete object[key];
}
// If there was only one argument (the previous loop didn't execute):
else for (key in object) {
if (hasOwnKey(object, key)) delete object[key];
}
};
<br>
pensamentos?