数组和循环结合起来非常强大。
var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
console.log(alphabet.join(''));
while (alphabet.length > 0) {
alphabet.shift();
console.log(alphabet.join(''));
}
编辑:
如果你真的需要你的递减字母左填充,你可以使用这个:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var letters = alphabet.split('');
var addPadding = (function (minLength) {
return function (shortString) {
if (shortString.length < minLength) {
return new Array(
minLength - shortString.length + 1
).join(' ') + shortString;
}
};
}(alphabet.length));
console.log(alphabet);
while (letters.length > 0) {
letters.shift();
console.log(addPadding(letters.join('')));
}
编辑:
这是一个更简单的答案:
function decrementingAlphabet () {
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
function iterate(spaces, letters) {
if (letters.length > 0) {
console.log(spaces + letters);
iterate(spaces + ' ', letters.substring(1));
} else {
return;
}
}
iterate('', alphabet);
}