search
HomeWeb Front-endJS TutorialJavaScript print star pyramid function

JavaScript print star pyramid function

Jan 30, 2018 pm 01:19 PM
javascriptjspyramid

This article mainly introduces JavaScript to realize the function of printing star pyramid. It 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 who need it can refer to it. I hope it can help. Everyone.

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

I guess everyone has seen this question when they were learning C language...

That is, print the following The ghost thing:

When I saw the loop structure, I felt very bored, so I disdained this question and didn’t think about it carefully, 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 utf-8 encoding is not used here is because utf-8 is suitable for nbsp's processing and * font will cause layout confusion, that is, the standard Song font is not used, making 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 sake of 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 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. 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 do I need to judge n++ first and then n%2!=0, that is, judging 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>

Related recommendations:

JavaScript method of printing debugging information (Jquery)

Javascript script to print part of the content of the web page_javascript skills

JavaScript print iframe content sample code_javascript skills

The above is the detailed content of JavaScript print 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
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.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft