search
HomeWeb Front-endJS TutorialImplementation example of JavaScript printing star pyramid function

This article mainly introduces JavaScript to realize the function of printing star pyramid, and combines specific examples to analyze the principle and related implementation techniques of JavaScript for outputting any given number of rows of star pyramid graphics. Friends in need can refer to the following

The example in this article describes how to implement the printing star pyramid function in JavaScript. I share it with you for your reference. The details are as follows:

It is exactly the same for you to write in other languages.

I guess you have seen this question when you were learning C language...

That is to say, print the following ghost stuff:

#When I saw the loop structure, I felt very bored, so I disdained this question and did not pay attention to it. Think about it,

Because if it is written in JavaScript, it can be written like this. It is not even JavaScript, it is just an html:


<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=gb2312"/>
</head>
<body>
&nbsp;&nbsp;*
&nbsp;***
*****
&nbsp;***
&nbsp;&nbsp;*
</body>
</html>

The reason why it is not used here UTF-8 encoding is because UTF-8's processing of nbsp and * font will cause typesetting confusion, that is, it does not use standard Song fonts, which makes the final result impossible to view.

Anyway, I can copy and paste the above content no matter how many lines you put in the question. However, today, when I have programmed to a certain amount and have some big data concepts, I saw this question again and carefully After thinking about it for a while, if the question maker asked to output a star-shaped pyramid with 200,000 lines of symmetry on the central axis, I would be damned.

So we still need to thoroughly understand how to implement this. Although such programming will not occur in actual programming, it is said that this question will still come up in some boring interviews. At least, latecomers will ask you C language When asked, if you output a star pyramid with 200,000 lines of symmetry on the central axis, you still have to know how to do it. If you can't do this question the first time, you can't do it.

1. Basic Goals

First, an input box pops up, allowing the user to enter an odd number. After all, axial symmetry requires an odd number,
Then for the robustness of the program, it is necessary to judge what the user inputs. If the input is not an odd number, a prompt will pop up and the subsequent program will not be executed. How to judge an odd number in JavaScript? I have already discussed it in "JavaScript's Judgment and Processing of Numbers" ” has been said before, so I won’t go into details here.

Considering the load of the browser, here, I only allow the odd number entered by the user to be 189. You can also increase it a bit. 189 feels okay in my computer, so I set this number. It has no special meaning. It was entered randomly and was not intentionally tested.

Enter a line of 189, and IE has already popped up a prompt to "abort the script", but there is no problem if you don't abort!

The running results are as follows:

If you are writing a C language program or other programs, this value can definitely be set larger!

2. Basic Idea

Once you understand this, it is very easy to write.

First of all, we only need to output spaces on the left side of *. There is no need to output spaces on the right side. After typing *, just change the line directly.

Split into two Parts, one part is when in/2 in the lower half.

The reason why it is divided like this is because the * sign in the output of these two parts It is different from the number of spaces output.

After that, it was a common problem in junior high school to find the rules. Anyway, I found the above rules, and there was no problem when programming and running. Other math emperors found more awesome expressions, and I was defeated.

3. Production process

The code is very simple, it is the expression of conditional structure and loop structure. It goes without saying that the above ideas are understood. .

Some people may find it strange here, why should I first judge n++ and then n%2!=0, that is, judge whether n+1 is an even number to judge whether n is an odd number,

The main thing here is It is to cater to the following for loop structure...


<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=gb2312"/>
</head>
<body>
</body>
</html>
<script>
var i,j,k,n;
n=window.prompt("请输入要输出的行数n,为了形成轴对称,所以你输出的必须是奇数!");
if(isNaN(n)||!n)
  alert("你输入的不是数!");
else{
  n++;
  if(n%2!=0)
    alert("你输入的不是奇数!");
  else if(n>190){
    alert("不要这么大嘛!臣妾做不到啊!");
  }
  else{
    for(i=1;i<n;i++){
      if(i<=n/2){
        for(k=n/2-i;k>0;k--)
          document.write("&nbsp;");
        for(j=0;j<2*i-1;j++)
          document.write("*");
          }
      else{
        for(k=i-n/2;k>0;k--)
          document.write("&nbsp;");
        for(j=0;j<2*(n-i)-1;j++)
          document.write("*");
        }
      document.write("<br>");
    }
  }
}
</script>

It will make me cry if I say too much, I will experience it myself...

The above is the detailed content of Implementation example of JavaScript printing star pyramid function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.