【问题标题】:function that takes a list of strings and prints them, one per line, in a rectangular frame获取字符串列表并在矩形框架中每行打印一个字符串的函数
【发布时间】:2021-12-10 11:56:22
【问题描述】:
  1. 编写一个函数,它接受一个字符串列表并将它们打印在一个矩形框架中,每行一个。例如列表 ["Hello", "World", "in", "a", "frame"] 打印为:
    *********
    * Hello *
    * World *
    * in    *
    * a     *
    * frame *
    *********

我的代码

    var x = "hello\nworld\nin\na\nframe";

function star(str) {
  let arr = [];
  arr = str.split("\n");
  for (let index = 0; index < 1; index++) {
    console.log("*******");
    for (let j = 0; j <= arr.length; j++) {
     arr == arr[j].split(",");
      console.log("*" + arr[j] + "*" );
    }
  }
  console.log("******");
  return arr;
}
console.log(star(x));

【问题讨论】:

  • 首先,尝试自己解决这个问题。并在此处粘贴您坚持使用的代码。这个门户不是用来解决你的作业的
  • 我试过但显示错误
  • 这是个问题吗?

标签: javascript reactjs


【解决方案1】:

我会这样做,但我相信还有更好的方法。

function makeStarBox(arr){
  const longest = arr.reduce((a, b) => a.length <= b.length ? b : a);
  const box_width = longest.length + 2;
  
  console.log("*".repeat(box_width));

  arr.map(str => console.log("*" + str + " ".repeat(box_width - (str.length + 2)) + "*"));

  console.log("*".repeat(box_width));
}

不过,您似乎确实在发布实际的家庭作业/考试问题,因此请务必研究代码并亲自了解它的实际作用。如果您不知道 mapreducerepeat 的作用,请查看文档并了解:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2020-01-27
    • 2017-09-24
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多