Home Web Front-end JS Tutorial Related examples of Math, arrays, and Date

Related examples of Math, arrays, and Date

May 21, 2018 pm 03:05 PM

math, arrays and dates are often encountered in learning, and this article will explain them.

Write a function that returns a random integer between min and max, including min but not including max

function getRandom (min,max) {    return Math.floor(Math.random()*(max-min) + min)
}//Math.floor 返回小于参数值的最大整数//Math.random 返回[0,1)之间的随机数
Copy after login

Write a function that returns a random integer between min and max, including min Including max

function getRandom (min,max) {    return Math.floor(Math.random()*(max-min+1) + min)
}
Copy after login

Write a function to generate a random string of length n. The value range of the string characters includes 0 to 9, a to z, A to Z

function getRandomStr (n) {    var dict = '0123456789'+               'abcdefghijklnmopqrstuvwxyz'+               'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; //一个字典;
    var string = &#39;&#39;;    for (i=0; i<n; i++) {
        string += dict[Math.floor(Math.random()*62)] ;
    }    return string ;
}
Copy after login

Write A function that generates a random IP address. A legal IP address is 0.0.0.0~255.255.255.255

function getRandIP(){    var ipArr = [];    for (i=0; i<4; i++) {
        ipArr.push(Math.floor(Math.random()*256)); //push()方法把元素从尾部放进数组;
    }    return ipArr.join(&#39;.&#39;);
}var ip = getRandIP()console.log(ip)
Copy after login

Write a function that generates a random color string. The legal color is #000000~ #ffffff

function getColor () {    var dict = &#39;0123456789abcdef&#39;
    var color = &#39;#&#39;;    for (i=0; i<6; i++) {
        color += dict[Math.floor(Math.random()*16)];
    }    return color;
}
getColor() ;
Copy after login

What are the functions of push, pop, shift, unshift, join, and splice in array methods? Use the splice function to implement the push, pop, shift, and unshift methods respectively.

The push() method can insert an element from the tail into the array and change the length and index of the original array;

var a =[] ;
a.push(4);
a ; // [4]

pop() method can delete and return the last element of the array and change the length and index of the original array ;

var a =[1,2] ;
a.pop(); // 2a ; // [1]

shift() method can convert the array Delete the first element from it and return the value of the first element, changing the length and index of the original array;

var a=[1,2,3,4];
a.shift (); //1;a; //[2,3,4]

The unshift() method adds one or more elements to the beginning of the array and returns the new length, changing Original array length and index;

var a=[1,2,3,4,5];
a.unshift(7,8); //7a; //[7,8, 1,2,3,4,5]

The splice() method can add/remove items to/from the array, and then return the deleted item. If it is not deleted, it will return an empty array and change the original Array length and index;

var a=[1,2,3];
a.splice(0,1); //[1]; //Start from position 0, delete 1 bit; a; //[2,3]
var a=[1,2,3];
a.splice(0,0,7,8); //[]; from bit 0 Start, delete 0 bits, insert 7,8 (inserted before); a; //[7,8,1,2,3];
var a=[1,2,3,4];
a.splice(1,1,7,8); //[2]; Starting from position 1, delete 1 position ([2]) and insert 7,8; ​​a; //[1,7,8 ,3,4];

Use splice() to implement push(), pop(), shift(), and unshift() methods;

var a =[1 ,2,3,4,5,6];
a.splice(a.length,0,n) // Implement push(), n is the element you want to pass in; a.splice(a.length -1,1) // Implement pop(); a.splice(0,1) // Implement shift(); a.splice(0,0,n) // Implement unshift(), n is what you want to pass in elements;

Write a function, operate the array, each item in the array becomes the original square, operate on the original array

function squareArr(arr){    for (i=0; i<arr.length; i++) {
        arr[i] = arr[i]*arr[i];
    }    return arr;
}var arr = [2, 4, 6]
squareArr(arr)console.log(arr) // [4,16,36]
Copy after login

Write a function, operate the array, return A new array, the new array only contains positive numbers, the original array remains unchanged

function filterPositive(arr){    var newArr = [];    var k = 0;    for (i=0; i<arr.length; i++) {        if (typeof arr[i] === &#39;number&#39;) {  //验证是否为数字
            if(arr[i]>0) {
                newArr[k] = arr[i];
                k++;
            }
        }
    }    return newArr;
}var arr = [3, -1,  2,  &#39;饥人谷&#39;, true]var newArr = filterPositive(arr)console.log(newArr) //[3, 2]console.log(arr) //[3, -1,  2,  &#39;饥人谷&#39;, true]
Copy after login

Write a function getChIntv to get the interval from the current time to the specified date

//示例var str = getChIntv("2017-02-08");console.log(str);  // 距除夕还有 20 天 15 小时 20 分 10 秒
 function getChIntv(date) {    var time = Math.abs(Date.now()-Date.parse(date));    var day = Math.floor(time/86400000);    var hour = Math.floor(time%86400000/3600000);    var min = Math.floor(time%86400000%3600000/60000)    var s = Math.floor(time%86400000%3600000%60000/1000)    var ms = (time%86400000%3600000%60000%1000);    return &#39;距离&#39;+date+&#39;: &#39;+day+&#39; 天 &#39;+hour+&#39; 小时 &#39;+min+&#39; 分钟 &#39;+s+&#39; 秒 &#39;+ms+&#39; 毫秒 &#39;}
getChIntv(&#39;2017-04-08&#39;)  //距离2017-04-08: 55 天 4 小时 0 分钟 45 秒 774 毫秒;
Copy after login

Put hh-mm- Change the dd format digital date to Chinese date

//示例var str = getChsDate(&#39;2015-01-08&#39;);console.log(str);  // 二零一五年一月八日
var dict ={0:&#39;零&#39;,1:&#39;一&#39;,2:&#39;二&#39;,3:&#39;三&#39;,4:&#39;四&#39;,5:&#39;五&#39;,6:&#39;六&#39;,7:&#39;七&#39;,8:&#39;八&#39;,9:&#39;九&#39;,            10:&#39;十&#39;,11:&#39;十一&#39;,12:&#39;十二&#39;,13:&#39;十三&#39;,14:&#39;十四&#39;,15:&#39;十五&#39;,16:&#39;十六&#39;,            17:&#39;十七&#39;,18:&#39;十八&#39;,19:&#39;十九&#39;,20:&#39;二十&#39;,21:&#39;二十一&#39;,22:&#39;二十二&#39;,23:&#39;二十三&#39;,            24:&#39;二十四&#39;,25:&#39;二十五&#39;,26:&#39;二十六&#39;,27:&#39;二十七&#39;,28:&#39;二十八&#39;,29:&#39;二十九&#39;,30:&#39;三十&#39;,31:&#39;三十一&#39;} function getCHT (date) {
    time = date.split(&#39;-&#39;);
    year = time[0].split(&#39;&#39;);    for (i=0; i<year.length; i++) {
        year[i] = dict[year[i]];
    }
    month = dict[parseInt(time[1])];
    day = dict[parseInt(time[2])];    return year.join(&#39;&#39;)+&#39; 年 &#39;+month+&#39; 月 &#39;+day+&#39; 日&#39;}
getCHT(&#39;2017-06-01&#39;) // 二零一七年六月一日;
Copy after login

Write a function, the parameter is the string format of the time object milliseconds, and the return value is a string. Assume that the parameter is the time object millisecond t, and the following strings are returned according to the time of t:

Just now (t is less than 1 minute interval from the current time)

3 minutes ago (t is less than 1 minute interval from the current time) The current time is greater than or equal to 1 minute and less than 1 hour)

8 hours ago (t is greater than or equal to 1 hour and less than 24 hours from the current time)

3 days ago (t is greater than or equal to the current time 24 hours, less than 30 days)

2 months ago (t is greater than or equal to 30 days from the current time and less than 12 months)

8 years ago (t is greater than or equal to 12 months from the current time )

//示例function friendlyDate(time){
}var str = friendlyDate( &#39;1484286699422&#39; ) //  1分钟前var str2 = friendlyDate(&#39;1483941245793&#39;) //4天前
function friendlyDate(time){    var nowT = Date.now();  //Date.now()获取当前时间距离1970年1月1日00:00:00的毫秒数
    pastT = nowT-time;    if (pastT<=60*1000) {        return &#39;刚刚&#39;
    }if (pastT>60000 && pastT<3600*1000) {        return Math.floor(pastT/60000)+&#39;分钟前&#39;
    }if (pastT>=3600*1000 && pastT<24*3600*1000) {        return Math.floor(pastT/(3600*1000))+&#39;小时前&#39;
    }if (pastT>=24*3600*1000 && pastT<30*24*3600*1000) {        return Math.floor(pastT/(24*3600*1000))+&#39;天前&#39;
    }if (pastT>=30*24*3600*1000 && pastT<12*30*24*3600*1000) {        return Math.floor(pastT/(30*24*3600*1000))+&#39;月前&#39;
    }else {        return Math.floor(pastT/(360*24*3600*1000))+&#39;年前&#39;
    }
}
friendlyDate(1496246400000) //一天前;
Copy after login

This article explains in detail the content and examples related to math, arrays and date. For more related content, please pay attention to the PHP Chinese website.

Related recommendations:

HTML5/CSS3 related knowledge explanation

Summary of common APIs used by Javascript to operate DOM

JavaScript complete summary of timer & DOM document

The above is the detailed content of Related examples of Math, arrays, and Date. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

From Websites to Apps: The Diverse Applications of JavaScript From Websites to Apps: The Diverse Applications of JavaScript Apr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles