如何打印'*'的菱形字符串javascript [英] How to print diamond shaped string of '*' javascript

查看:257
本文介绍了如何打印'*'的菱形字符串javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力用Javscript打印出菱形的弦.我想知道如何以正确的顺序插入空格.首先,我尝试打印一个三角形,然后将其倒置并加入它们.
但是我在尝试打印三角形时被卡住了.

我尝试过的事情:

I have been struggling to print a diamond shaped string with Javscript. I would like to know how I can insert spaces in the correct order. First, I was trying to print out a triangle and then I would turn it upside down and join them.
But I was stuck while trying to print the triangle.

What I have tried:

function diamond(arg) {
  if(arg === 1) {return "*"}
  var str = ""
  
   for(var j = arg; j > 1; j--) {
     str += Array(j).join(' ') + Array(j).join('*') + '\n'
    }
     
  
  return str
}
diamond(5) ->

    ****
   ***
  **
 *


但我希望它打印出来


But I would like it to print this

 **
****

推荐答案

建议:
-拿一张纸(有正方形)
-绘制所需的形状
-逐行分析您需要做什么(空格数和星星数)
-比较需求从一行到另一行的变化.

如果可以简化您的代码,请为上半部分编写一段代码,为下半部分编写一个代码.
Advice:
- Take a sheet of paper (with squares)
- Draw the shape you want
- Analyze line by line what you need to do (number of spaces and number of stars)
- Compare how the needs change from a line to the next.

If it can simplify for you, make a piece of code for top half and anothe one for bottom half.


这篇关于如何打印'*'的菱形字符串javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆