A brief analysis of JS dates, Math, arrays and objects
This article mainly shares with you a brief analysis of JS dates, Math, arrays and objects, hoping to help everyone.
Related questions
Get the date in 2017-06-10 format
function formatDate(dt){ if(!dt){ dt = new Date(); } var year = dt.getFullYear();var month = dt.getMonth()+1;var date = dt.getDate();if(month<10){ //强制类型转换 month = '0'+month; }if(date<10){ date = '0'+date; }return year + '-'+month+'-'+date; }var dt = new Date();var formatDate = formatDate(dt); console.log(format);
Get random Number, the requirement is a string format of consistent length (the role of random numbers in front-end development)
var random =Math.random();random= random + '0000000000';//保证下一句不会报错random = random.slice(0,9); console.log(random);
Write a general forEach that can traverse objects and arrays Function (available in jquery)
//想想对象中的forEach与数组中的for in怎么用比较好//这里是forEach函数function forEach(obj,fn){ var key; if(obj instanceof Array){ obj.forEach(function(item,index){ fn(index.item); }) }else{ for(key in obj){ fn(key.obj[key]); } } }//调用var arr = [1,2,3];forEach(arr,function(index,item)){ console.log(index.item); }var obj = {x:100,y:200};forEach(obj,function(key,value){ console.log(key,value); })
Knowledge point
Date
Date.nowTime(); //获取当前时间毫秒数(这个数是从1970开始算起到现在走了多少毫秒数)var myDate = new Date(); //new一个时间对象myDate.getTime(); //获取毫秒数myDate.getFullYear(); //年(4位数),还有一种getYear()的方法,有兼容性的问题,与getFullYear()相差1900myDate.getMonth(); //月(0-11),实际应用是应该注意它的返回值myDate.getDate();//日(1-31)myDate.getDay();//星期(0-6),实际应用是应该注意它的返回值myDate.getHours();//时(0-23)myDate.getMinutes();//分(0-59)myDate.getSeconds();//秒(0-59)
-
Math
1. Get a random number Math.random();
will return a decimal number greater than 0 and less than 1, eg: 0.14249200181060218, which is generally used to clear cache For example: when the page is opened, due to the existence of cache, the newly updated data sometimes cannot be refreshed on the page, because if the requested address is the same, the browser will not connect to the server. At this time, random numbers can be used to process it, which is equivalent to loading a new page.
在URL 参数后加上 "?r=" + Math.random();//加随机数在 URL 参数后加上 "?timestamp=" + new Date().getTime(); //也可以加时间戳
2. For more methods and random number extensions, see my previous blog;
Array API
1. forEach traverses all elements
var arr = [1,2,3]; arr.forEach(function(item,index){//item为元素的值eg:1,2,3,index位为元素的位置,从0开始的 //遍历数组中所有元素 console.log(index,item); //注意参数顺序});
2 . every determines whether all elements meet the conditions
var arr = [1,2,3];var result = arr.every(funciton(item,index){// 用来判断所有的数组元素,都满足一个条件 if(item < 4){ return ture; } }); console.log(result);//true
3 . some determines whether at least one element meets the conditions
var arr = [1,2,3];var result = arr.every(funciton(item,index){// 用来判断所有的数组元素,都满足一个条件 if(item < 2){ return ture; } }); console.log(result);//true
4 . sort Sort (from small to large) Sort toward larger)
var arr = [1,4,3,2,5];var arr2 = arr.sort(function(a,b){ //从小到大 return a-b; //从大到小 //return b-a;}); console.log(arr2);//[1,2,3,4,5]
5. map reassembles the elements to generate a new array (assembly of elements into another type of elements according to a rule to generate a new array)
var arr = [1,2,3,4];var arr2 = arr.map(function(item,index){ //将元素重新组装并返回 return '<b>'+item+'</b>'; });console.log(arr2); //["<b>1</b>", "<b>2</b>", "<b>3</b>", "<b>4</b>"]
6. Filter elements that meet the conditions
var arr = [1,2,3];var arr2 = arr.filter(function(item,index){ //通过一个条件过滤数组 if(item>=2){ return true; } }); console.log(arr2); //2,3
Object API
var obj ={x:100,y:200,z:300};var key;for(key in obj){//key这里取得是obj的属性名 if(obj.hasOwnProperty(key)){//判断他是这个obj的属性而不是原型的属性 console.log(key,obj[key]); } }
Related recommendations:
JS date object simple operation (Get the current year, week, and time)
JS date addition and subtraction function sorting
js date related function summary sharing_javascript skills
The above is the detailed content of A brief analysis of JS dates, Math, arrays and objects. 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

AI Hentai Generator
Generate AI Hentai for free.

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



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

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

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

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

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values are passed and object references are passed.

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

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
