Home Web Front-end JS Tutorial About JS time object and recursion issues

About JS time object and recursion issues

May 21, 2018 am 11:30 AM
javascript recursion question

JS time objects and recursion are often encountered in learning, and this article will explain them.

What are the basic types? What are the complex types? What are the characteristics?
Generally speaking, the basic types of JS are mainly divided into 5 types, which refer to simple data segments stored in stack memory;

Number: number

Boolean values: true, false

String: string

null: Control pointer

underfined: There is a pointer but no value is assigned

Complex types only have object: including arrays, objects, and functions , Regular refers to the object saved in the heap memory. What is saved in the variable is actually just a pointer (coordinate). This pointer executes another location in the memory, and the object is saved at this location.

The output of the following code? Why?

var obj1 = {a:1, b:2};var obj2 = {a:1, b:2};console.log(obj1 == obj2); //Determine whether obj1 is equal to obj2console.log(obj1 = obj2); //Assign obj2 to obj1console.log(obj1 == obj2); //Determine again whether obj1 is equal to obj2 because of the characteristics of complex types. The two objects are at different positions, so the result is: falseObject {a: 1, b: 2}true

Code

Write a function getIntv to get the time from the current time to Specify the interval between dates

1

2

3

4

5

6

7

8

9

function getIntv(haha){

  a= Date.now();

  b= Date.parse(haha);

  c= b-a;

  d= Math.floor(c/(1000*60*60*24));

  e= Math.floor((c-d*1000*60*60*24)/(1000*60*60));

  f= Math.floor((c-d*1000*60*60*24-e*1000*60*60)/(1000*60));

  g= Math.floor((c-d*1000*60*60*24-e*1000*60*60-f*1000*60)/1000);  return ("距除夕还有"+d+"天"+e+"小时"+f+"分钟"+g+"秒")

}var str = getIntv("2017-01-27");console.log(str);

Copy after login

Change the digital date to a Chinese date

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

function getChsDate(lala){

  num=['零','一','二','三','四','五','六','七','八','九','十','十一','十二','十三','十四','十五','十六','十七','十八','十九','二十','二十一','二十二','二十三','二十四','二十五','二十六','二十七','二十八','二十九','三十','三十一']  var damo = lala.split('-')    

  var b = damo[0].split('')   

 for( var e =0 ;e< damo.length; e++) {

  for(var i = 0 ;i< b.length ; i++) { 

    for(var f = 0 ;f< num.length ;f++) {  

      if( damo[e] == f.toString() ) {

        damo[e] = num[f]

      }      if( b[i] == f.toString() ) {

        b[i] = num[f]

      }

    }

  }

 

  return ( b.join("")+"年"+damo[1]+"月"+damo[2]+"日" )

}var str = getChsDate("2015-11-31")console.log(str)

Copy after login

Write a function to get the date n days ago

1

2

3

function getLastNDays(lala) {  var damo = new Date().getTime()-(lala*1000*60*60*24);  var d2 = new Date(damo)  var ad =(d2.getMonth()+1)  console.log(d2.getFullYear()+&#39;-&#39;+ad+&#39;-&#39;+d2.getDate())  

}

 getLastNDays(40);

Copy after login

Complete the following code to obtain execution The time is like:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

var Runtime = (function(){    var a,b,c;    return {        start: function(){

             a = Date.now();   //获取现在的时间

             console.log(a);

        },        end: function(){

             b = Date.now();    //获取执行后的时间

             console.log(b);

        },        get: function(){

             c = b - a;              //两者相减得出执行代码的时间。           

             return (c+"毫秒");        //单位为毫秒

        }

    };

}());

Runtime.start();            

for(var i = 0; i<60000 ;i++ ){        

                                   //这里计算i循环60000次所需要的时间}

Runtime.end();console.log(Runtime.get());

Copy after login

There are 200 steps in the stairs. Each time you take 1 or 2 levels, how many ways are there in total from the bottom to the top? Use code (recursion) to implement

1

2

3

function fn(sum){  if(sum===1){    return 1;

  if(sum===2){    return 2;

  return fn(sum-1)+fn(sum-2)

Copy after login

}//The walking method of the stairs is equivalent to (the subsequent walking method after taking one step) (the subsequent walking method after taking two steps)//taking one step or two steps is Condition console.log(fn(200));                                                                                                             ’ to ’ s ’ to ’ s ’ s           ‐ ‐ ‐ ‐ ‐‐‐‐ ​ ​ ​ // If the value is too large, it will get stuck.

Write a deep copy method of json object. The json object can be nested in multiple layers, and the value can be a character. String, number, Boolean, any item in the json object

1

2

3

4

5

6

7

8

9

10

var obj={  sex:18,  vala:"hello",  arr:{    name:"damo"

  }

};function objcopy(obj){  var newobj={};  for(var i in obj){    //遍历对象obj

    if(typeof obj[i]=== "object"){       //如果对象的值为对象

      newobj[i] = objcopy(obj[i])    //将对象赋值为新对象

    }else{

      newobj[i]=obj[i];

    }

  return newobj;

}var newobj= objcopy(obj);console.log(newobj)                 //一个新的对象与原对象无关系

Copy after login

Write a deep copy method of the array. The value in the array can be a string, number, Boolean, or any item in the array

1

2

3

4

5

6

7

8

var arr=[18, "hello", [2,3,5,6,9],true,];function objcopy(arr){  var newarr=[];  for(var i in arr){    //遍历数组arr

    if( arr[i] instanceof Array){    //条件:如果对象的值为数组

      newarr[i] = objcopy(arr[i])    //将数组内容赋值为新数组

    }else{

      newarr[i]=arr[i];

    }

  return newarr;

}var newarr= objcopy(arr);console.log(newarr)                 //一个新的数组与原数组无关系

Copy after login

Write a deep copy method. The copied object and the internal nested value can be any item among strings, numbers, Boolean, arrays, and json objects

1

2

3

4

5

function   arrcopy(num){   var lala;  if(num instanceof Array){

    lala = [];

  } else{

    lala={};

  }

Copy after login

1

2

3

4

5

6

7

for(var key in num){    if(num[key] instanceof Array){

       lala[key] = arrcopy(num[key]);

    }    else{

       lala[key] = num[key];

    }

  return lala;

}var lala= arrcopy(arr);

Copy after login

This article will do it

Related recommendations:

What is the difference between innerText and innerHTML of dom objects?

Some basic questions about JS

How to modularize require.js with front-end js

The above is the detailed content of About JS time object and recursion issues. 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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Recursive implementation of C++ functions: Is there a limit to recursion depth? Recursive implementation of C++ functions: Is there a limit to recursion depth? Apr 23, 2024 am 09:30 AM

The recursion depth of C++ functions is limited, and exceeding this limit will result in a stack overflow error. The limit value varies between systems and compilers, but is usually between 1,000 and 10,000. Solutions include: 1. Tail recursion optimization; 2. Tail call; 3. Iterative implementation.

Do C++ lambda expressions support recursion? Do C++ lambda expressions support recursion? Apr 17, 2024 pm 09:06 PM

Yes, C++ Lambda expressions can support recursion by using std::function: Use std::function to capture a reference to a Lambda expression. With a captured reference, a Lambda expression can call itself recursively.

Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Apr 22, 2024 pm 03:18 PM

The recursive algorithm solves structured problems through function self-calling. The advantage is that it is simple and easy to understand, but the disadvantage is that it is less efficient and may cause stack overflow. The non-recursive algorithm avoids recursion by explicitly managing the stack data structure. The advantage is that it is more efficient and avoids the stack. Overflow, the disadvantage is that the code may be more complex. The choice of recursive or non-recursive depends on the problem and the specific constraints of the implementation.

C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application Apr 30, 2024 am 10:45 AM

Tail recursion optimization (TRO) improves the efficiency of certain recursive calls. It converts tail-recursive calls into jump instructions and saves the context state in registers instead of on the stack, thereby eliminating extra calls and return operations to the stack and improving algorithm efficiency. Using TRO, we can optimize tail recursive functions (such as factorial calculations). By replacing the tail recursive call with a goto statement, the compiler will convert the goto jump into TRO and optimize the execution of the recursive algorithm.

Detailed explanation of C++ function recursion: application of recursion in string processing Detailed explanation of C++ function recursion: application of recursion in string processing Apr 30, 2024 am 10:30 AM

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

How to solve the problem that jQuery cannot obtain the form element value How to solve the problem that jQuery cannot obtain the form element value Feb 19, 2024 pm 02:01 PM

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

Detailed explanation of C++ function recursion: tail recursion optimization Detailed explanation of C++ function recursion: tail recursion optimization May 03, 2024 pm 04:42 PM

Recursive definition and optimization: Recursive: A function calls itself internally to solve difficult problems that can be decomposed into smaller sub-problems. Tail recursion: The function performs all calculations before making a recursive call, which can be optimized into a loop. Tail recursion optimization condition: recursive call is the last operation. The recursive call parameters are the same as the original call parameters. Practical example: Calculate factorial: The auxiliary function factorial_helper implements tail recursion optimization, eliminates the call stack, and improves efficiency. Calculate Fibonacci numbers: The tail recursive function fibonacci_helper uses optimization to efficiently calculate Fibonacci numbers.

What are the debugging techniques for recursive calls in Java functions? What are the debugging techniques for recursive calls in Java functions? May 05, 2024 am 10:48 AM

The following techniques are available for debugging recursive functions: Check the stack traceSet debug pointsCheck if the base case is implemented correctlyCount the number of recursive callsVisualize the recursive stack

See all articles