Related examples of Math, arrays, and Date
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)之间的随机数
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) }
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 = ''; for (i=0; i<n; i++) { string += dict[Math.floor(Math.random()*62)] ; } return string ; }
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('.'); }var ip = getRandIP()console.log(ip)
Write a function that generates a random color string. The legal color is #000000~ #ffffff
function getColor () { var dict = '0123456789abcdef' var color = '#'; for (i=0; i<6; i++) { color += dict[Math.floor(Math.random()*16)]; } return color; } getColor() ;
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]
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] === 'number') { //验证是否为数字 if(arr[i]>0) { newArr[k] = arr[i]; k++; } } } return newArr; }var arr = [3, -1, 2, '饥人谷', true]var newArr = filterPositive(arr)console.log(newArr) //[3, 2]console.log(arr) //[3, -1, 2, '饥人谷', true]
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 '距离'+date+': '+day+' 天 '+hour+' 小时 '+min+' 分钟 '+s+' 秒 '+ms+' 毫秒 '} getChIntv('2017-04-08') //距离2017-04-08: 55 天 4 小时 0 分钟 45 秒 774 毫秒;
Put hh-mm- Change the dd format digital date to Chinese date
//示例var str = getChsDate('2015-01-08');console.log(str); // 二零一五年一月八日 var dict ={0:'零',1:'一',2:'二',3:'三',4:'四',5:'五',6:'六',7:'七',8:'八',9:'九', 10:'十',11:'十一',12:'十二',13:'十三',14:'十四',15:'十五',16:'十六', 17:'十七',18:'十八',19:'十九',20:'二十',21:'二十一',22:'二十二',23:'二十三', 24:'二十四',25:'二十五',26:'二十六',27:'二十七',28:'二十八',29:'二十九',30:'三十',31:'三十一'} function getCHT (date) { time = date.split('-'); year = time[0].split(''); 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('')+' 年 '+month+' 月 '+day+' 日'} getCHT('2017-06-01') // 二零一七年六月一日;
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( '1484286699422' ) // 1分钟前var str2 = friendlyDate('1483941245793') //4天前 function friendlyDate(time){ var nowT = Date.now(); //Date.now()获取当前时间距离1970年1月1日00:00:00的毫秒数 pastT = nowT-time; if (pastT<=60*1000) { return '刚刚' }if (pastT>60000 && pastT<3600*1000) { return Math.floor(pastT/60000)+'分钟前' }if (pastT>=3600*1000 && pastT<24*3600*1000) { return Math.floor(pastT/(3600*1000))+'小时前' }if (pastT>=24*3600*1000 && pastT<30*24*3600*1000) { return Math.floor(pastT/(24*3600*1000))+'天前' }if (pastT>=30*24*3600*1000 && pastT<12*30*24*3600*1000) { return Math.floor(pastT/(30*24*3600*1000))+'月前' }else { return Math.floor(pastT/(360*24*3600*1000))+'年前' } } friendlyDate(1496246400000) //一天前;
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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'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 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 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.

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.

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.

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.
