编写一个函数,它接受一个字符串列表打印它们,每行一个,在矩形框架中

时间:2017-05-01 09:36:39

标签: javascript html5 css3

例如,列表["Hello", "World", "in", "a", "frame"]打印为:

*********
* Hello *
* World *
* in    *
* a     *
* frame *
*********

1 个答案:

答案 0 :(得分:0)

完全相同的功能:



function printFrame(arr) {
    function fill (str, length, char) {
      return (str.length < length) ? fill(str + char, length, char) : str;
    }
    
    let size = arr.map((str) => {
            return str.length;
        })
        .reduce((a, b) => {
            return Math.max(a, b);
        });
    
    let line = fill('', size + 4, '*');
    
    arr = arr.map((element) => {
            return '* '+ fill(element, size, ' ') + ' *';
        })
    arr.unshift(line);
    arr.push(line);
    
    return arr.join('\n');;
}

console.log(printFrame(["Hello", "World", "in", "a", "frame"]));
&#13;
&#13;
&#13;