这是一个解决方案,它允许在不添加更多条件的情况下使用动态的倍数列表。
// List of outputs
var outputs = [
{mult: 3, str: 'ping'},
{mult: 5, str: 'pong'}
// {mult: 10, str: 'play'} ex: [30] => 'pingpongplay'
];
// Loop 100 times
for (var i = 1, j = 100; i <= j; i += 1) {
// Set empty vars
var result, string = '';
// Loop through the listed output objects
outputs.forEach(function (output) {
// If listed multiple, concat string
if (i % output.mult === 0) {
string += output.str;
}
});
// Set result
if (string.length) {
result = string;
} else {
result = i;
}
// print result
document.body.innerHTML += result + '<br>';
}
作为通过 jslint 的函数:
/*jslint browser: true */
var printOutputs = function (array, iterations) {
'use strict';
var i = 1;
var outputResults = function (arr, idx) {
var result;
var str = '';
arr.forEach(function (item) {
if (idx % item.mult === 0) {
str += item.str;
}
});
if (str.length) {
result = str;
} else {
result = idx;
}
return result;
};
while (i < iterations) {
document.body.innerHTML += outputResults(array, i) + '<br>';
i += 1;
}
};
var outputs = [
{mult: 3, str: 'ping'},
{mult: 5, str: 'pong'}
];
printOutputs(outputs, 100);
为了好玩,一个缩小的 ES6 版本:
const pO=(arr,itr)=>{let i=1,o=(a,idx)=>{let r,s='';a.map(v=>{if(idx%v.mult===0)s+=v.str});s.length?r=s:r=idx;return r};while(i<itr){document.body.innerHTML+=`${o(arr,i)}<br>`;i++}};
pO([{mult:3,str:'ping'},{mult:5,str:'pong'}], 100);