Table of Contents
How many days are calculated?
JS implementation of factorial
Judge prime numbers
js Fibonacci sequence summation
Recursive algorithm
Dynamic programming
Iteration method
Prime numbers
Home Web Front-end JS Tutorial Introducing a small case for getting started with JS

Introducing a small case for getting started with JS

Jun 15, 2018 pm 03:23 PM
javascript

How many days are calculated?

1, whether the year is a leap year, confirm the number of days in February
2, get the number of days in each month, which can be put in the array
3, get the number of days in the current month according to the month
4. The number of days obtained by adding 3 to the date is ok.

1

2

3

4

5

6

7

8

9

10

11

function isLeapYr(yr) {

    //判断闰年

    return (yr % 4 === 0 && yr % 100 !== 0) || (yr % 100 === 0 && yr % 400 === 0);

}function count(y, m, d) {

    var mdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];    var mSum = 0;    var sum = 0;    //如果是闰年的话,那么2月份就应该有29天

    isLeapYr(y) ? mdays[1] = 29 : mdays[1];    //计算该月份之前的总天数,比如m=3,那么就计算1和2月的总天数

    for (var i = 0; i < m - 1; i++) {

        mSum += mdays[i];

    }    //加上当月天数

    sum = mSum + d;    return sum;

}

Copy after login

1

2

3

4

5

6

7

8

9

10

11

12

13

14

//弹出年、月、日输入框,声明年鱼儿,并赋值

   var y =parseInt(prompt("请输入你的出生年份"));    var m = parseInt(prompt("请输入你的出生月份"));    var d =parseInt(prompt("请输入你的出生日期"));    //月

   //求各月份数字之和

   var getMonth=new Array(31,28,31,30,31,30,31,31,30,31,30);    var sum1=0,i;    for(i=0;i<m-1;i++){

       sum1+=getMonth[i]

       }    //年

   //判断年是否为闰年,是且大于2月份加一

       if(( y%400 ==0||(y % 4 == 0&& y%100 !=0))&& m > 2){

           sum=sum1 + d +1;

           document.write("该天为一年中的第"+sum+"天");

       }else{

           sum=sum1+d;

           document.write("该天为一年中的第"+sum+"天");

       }

Copy after login

Use time function for calculation

1

var now = new Date();//输入日期以今日为例var NewYearsDay = new Date(now.getFullYear(), 0, 0, 0, 0, 0);//该年第一天console.log((now.getTime()-NewYearsDay.getTime())/86400000>>>0)//算出两者的时间戳之差就是时间差的微秒数  再用时间差除以天的微秒数86400000 取整 就是第几天

Copy after login

1

2

3

4

var endDate = new Date(y, m-1, d),

    startDate = new Date(y, 0, 0),

    days = (endDate - startDate) / 1000 / 60 / 60 / 24;

document.write("该天为一年中的第"+ days +"天");

Copy after login

JS implementation of factorial

1

2

3

4

5

6

7

//while循环实现function calNum(n) {

    var product = 1;    while(n > 1){//1*5*4*3*2,1*n*(n-1)*(n-2)*...*2

        product *= n;

        n--;

    }    return product;

}

console.log(calNum(5))

Copy after login

1

2

3

4

5

6

7

//for循环实现

   function calNum(n){

        var a = 1, str = &#39;1*&#39;;        for (var i = 2; i <= n; i++) {            str += i + &#39;*&#39;;

            a *= i;

        }        str = str.substr(0,str.length-1);        return str + &#39;=&#39; +a;

    }

    console.log(calNum(5));

Copy after login

Judge prime numbers

1

2

3

4

5

6

7

8

9

10

11

12

var prime = function(len){

    var i,j;

    var arr = [];  for(i = 1; i < len; i++){

    for(j=2; j < i; j++){ 

      if(i%j === 0) {

         break;

      }

    }    if(i <= j && i !=1){

      arr.push(i);

    }

  return arr;

};console.log(prime(100));

Copy after login

js Fibonacci sequence summation

Recursive algorithm

The time complexity is O(2^n), the space complexity is O(n)

1

2

3

4

5

6

function recurFib(n) {

 if (n < 2) {    return n;

 else {    return recurFib(n-1) + recurFib(n-2);

 }

}

 alert(recurFib(10));//将显示55

Copy after login

Dynamic programming

The time complexity is O( n), the space complexity is O(n)

1

2

3

4

5

6

function dynFib(n) {     var res = [1,1]; 

  if (n == 1 || n == 2) {      return 1;

  }      for (var i = 2; i < n; i++) {        val[i] = val[i-1] + val[i-2];

    }      return val[n-1];

}

alert(dynFib(10));//将显示55

Copy after login

Iteration method

The time complexity is O(n), the space complexity is O(1)

1

2

3

4

5

6

7

8

function iterFib(n){

 var last=1;  var nextlast=1;  var result=1;  for(var i=2;i<n;i++){

   result=last+nextlast;

   nextlast=last;

   last=result;

 return result;

}

alert(iterFib(10));//将显示55

Copy after login

Prime numbers

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

function foo(n){ 

  var a=[],state=0; 

  for(var i=2;i<n;i++){ 

    var sqrt_i = Math.sqrt(i); 

    if(i%sqrt_i===0){ 

      continue

    

    for(var j=2;j<sqrt_i;j++){ 

      if(i%j===0){ 

        state=1; 

        break

      }else

        state=0; 

      

    

   if(state===0){ 

     a.push(i); 

   

  

  console.log(a); 

foo(100)

Copy after login

This article explains a small case for getting started with JS. For more related content, please pay attention to the php Chinese website.

Related recommendations:

Achieving dynamic display of processes through js

##particlesJS usage introduction related content

Detailed analysis of operators i and i in JS


The above is the detailed content of Introducing a small case for getting started with JS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles