Table of Contents
Related questions
Knowledge point
Home Web Front-end JS Tutorial A brief analysis of JS dates, Math, arrays and objects

A brief analysis of JS dates, Math, arrays and objects

Mar 05, 2018 am 11:02 AM
javascript math object

This article mainly shares with you a brief analysis of JS dates, Math, arrays and objects, hoping to help everyone.

  • 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 = &#39;0&#39;+month;
}if(date<10){    date = &#39;0&#39;+date;
}return year +  &#39;-&#39;+month+&#39;-&#39;+date;
}var dt = new Date();var formatDate = formatDate(dt);
console.log(format);
Copy after login
  • 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 + &#39;0000000000&#39;;//保证下一句不会报错random = random.slice(0,9);
console.log(random);
Copy after login
  • 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);
})
Copy after login

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)
Copy after login
  • 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(); //也可以加时间戳
Copy after login

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);    //注意参数顺序});
Copy after login

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
Copy after login

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
Copy after login

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]
Copy after login

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 &#39;<b>'+item+'</b>';
});console.log(arr2);  //["<b>1</b>", "<b>2</b>", "<b>3</b>", "<b>4</b>"]
Copy after login

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
Copy after login
  • 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]);
    }
}
Copy after login

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!

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

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 convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

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

What is the difference between arrays and objects in PHP? What is the difference between arrays and objects in PHP? Apr 29, 2024 pm 02:39 PM

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.

What is the Request object in PHP? What is the Request object in PHP? Feb 27, 2024 pm 09:06 PM

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

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

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.

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