Web Front end "sixth piece" JavaScript object

Source: Internet
Author: User
Tags time zones



Data types other than null and undefined are defined as objects in JavaScript, and variables can be defined using the method of creating objects, String, Math, Array, Date, RegExp are important built-in objects in JavaScript, and most of the functionality in JavaScript programs is based on object implementations.

<script language = "javascript">
var aa = Number.MAX_VALUE;
// Using a digital object to obtain the maximum number that can be represented
var bb = new String ("hello JavaScript");
// Create a string object
var cc = new Date ();
// Create a date object
var dd = new Array ("Monday", "Tuesday", "Wednesday", "Thursday");
// Array object
</ script>
 

First, the string object (string)

1. String object creation

String creation (two ways)
       ① variable = "string"
       ② string object name = new String (string)

// ==========================
// There are two ways to create a string object
//        method one
          var s = ‘sffghgfd’;
// way two
          var s1 = new String (‘hel lo‘);
          console.log (s, s1);
          console.log (typeof (s)); // object type
          console.log (typeof (s1)); // string type
 

2. Properties and functions of string objects

-------Attributes
x.length --- --- get the length of the string

------method
 x.toLowerCase () --- --- lower case
 x.toUpperCase () ------- Uppercase
 x.trim () --- --- remove spaces on both sides of the string


---- String query method

x.charAt (index) --- --- str1.charAt (index); ----Get the character at the specified position, where index is the character index to be obtained

x.indexOf (index) --- --- query string position
x.lastIndexOf (findstr)

x.match (regexp) --- --match returns an array of matching strings, or null if there is no match
x.search (regexp) ----search returns the index of the first character position of the matched string

                        Example:
                        var str1 = "welcome to the world of JS!";
                        var str2 = str1.match ("world");
                        var str3 = str1.search ("world");
                        alert (str2 [0]); // result is "world"
                        alert (str3); // result is 15
                        

---- Substring processing method

x.substr (start, length) --- --- start represents the starting position, length represents the interception length
x.substring (start, end) ----- end is the end position

x.slice (start, end) --- --- slice operation string
                        Example:
                            var str1 = "abcdefgh";
                            var str2 = str1.slice (2,4);
                            var str3 = str1.slice (4);
                            var str4 = str1.slice (2, -1);
                            var str5 = str1.slice (-3, -1);

                            alert (str2); // result is "cd"
                            
                            alert (str3); // result is "efgh"
                            
                            alert (str4); // result is "cdefg"
                            
                            alert (str5); // result is "fg"

x.replace (findstr, tostr) --- --- string replacement

x.split (); --- --- split string
                                 var str1 = "one, two, three, four, five, six, sun";
                                var strArray = str1.split (",");
                                alert (strArray [1]); // The result is "two"
                                
x.concat (addstr) --- --- stitching strings
Use of methods

<script>
// ==========================
// There are two ways to create a string object
//        method one
          var s = ‘sffghgfd’;
// way two
          var s1 = new String (‘hel lo‘);
          console.log (s, s1);
          console.log (typeof (s)); // object type
          console.log (typeof (s1)); // string type

// =======================
// Properties and methods of string objects
// 1. String is such a property
        console.log (s.length); // Get the length of the string

// 2. String method
        console.log (s.toUpperCase ()); // Capitalize
        console.log (s.toLocaleLowerCase ()); // Lower case
        console.log (s1.trim ()); // Remove spaces on both sides of the string (same as strip method in python, will not remove spaces in the middle)
//// 3. String query method
        console.log (s.charAt (3)); // Get the character at the specified index position
        console.log (s.indexOf (‘f’)); // If there are duplicates, get the index of the first character, or -1 if there is no character you are looking for in the string
        console.log (s.lastIndexOf (‘f’)); // If there are duplicates, get the index of the last character
        var str = ‘welcome to the world of JS!’;
        var str1 = str.match (‘world’); // match returns an array of matching strings, or null if there is no match
        var str2 = str.search (‘world’); // search returns the index of the matched string from the first character position, or -1 if not
        console.log (str1); // Print
        alert (str1); // popup
        console.log (str2);
        alert (str2);


// ======================
// substring processing method
        var aaa = ‘welcome to the world of JS!’;
        console.log (aaa.substr (2,4)); // Indicates that four are intercepted from the second position
        console.log (aaa.substring (2,4)); // Index starts from the second to the fourth, pay attention to the end
        // Slicing operation (the same as in python, both are careless)
        console.log (aaa.slice (3,6)); // From the third to the sixth
        console.log (aaa.slice (4)); // From the fourth one onwards
        console.log (aaa.slice (2, -1)); // From the second to the last
        console.log (aaa.slice (-3, -1));


// string replacement ,,
        console.log (aaa.replace (‘w‘, ’c’)); // String replacement, only one can be replaced
        // and all can be replaced in python
        console.log (aaa.split (‘‘)); // The string is split by spaces
        alert (aaa.split (‘‘)); // The string is split by spaces
        var strArray = aaa.split (‘‘);
        alert (strArray [2])
    </ script>


Array object (array)

1. Three ways to create arrays

Creation method 1:
var arrname = [element 0, element 1, ....]; // var arr = [1,2,3];

Creation method 2:
var arrname = new Array (element 0, element 1, ....); // var test = new Array (100, "a", true);

Creation method 3:
var arrname = new Array (length);
            // Initialize the array object:
                var cnweek = new Array (7);
                    cnweek [0] = "Sunday";
                    cnweek [1] = "Monday";
                    ...
                    cnweek [6] = "Saturday";
2. Array Properties and Methods

// =====================
// Properties and methods of array objects
          var arr = [11,55, ‘hello’, true, 656];
// 1.join method
        var arr1 = arr.join (‘-‘); // Concatenate the array elements into a string and embed it into the array.
        alert (arr1); // And python is embedded into the string
// 2.concat method (link)
        var v = arr.concat (4,5);
        alert (v.toString ()) // return 11,55, ‘hello’, true, 656,4,5
// 3. Reserve sort
// reserve: inverted array elements
        var li = [1122,33,44,20, ‘aaa’, 2];
        console.log (li, typeof (li)); // Array [1122, 33, 44, 55] object
        console.log (li.toString (), typeof (li.toString ())); // 1122,33,44,55 string
        alert (li.reverse ()); // 2, ‘aaa’, 55,44,33,1122
// sort: sort array elements
        console.log (li.sort (). toString ()); // 1122,2,20,33,44, aaa is sorted by ascii code value
// What if you want to compare by numbers? (Just define a function)
//        method one
        function intsort (a, b) {
            if (a> b) {
                return 1;
            }
            else if (a <b) {
                return -1;
            }
            else {
                return 0;
            }
        }
        li.sort (intsort);
        console.log (li.toString ()); // 2,20,33,44,1122, aaa

// way two
        function Intsort (a, b) {
            return a-b;
        }
        li.sort (intsort);
        console.log (li.toString ());
        // 4.Array slice operation
        //x.slice(start,end);
        var arr1 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’];
        var arr2 = arr1.slice (2,4);
        var arr3 = arr1.slice (4);
        var arr4 = arr1.slice (2, -1);
        alert (arr2.toString ()); // The result is "c, d"
        alert (arr3.toString ()); // The result is "e, f, g, h"
        alert (arr4.toString ()); // The result is "c, d, e, f, g"
// 5.Delete the sub-array
        var a = [1,2,3,4,5,6,7,8];
        a.splice (1,2);
        console.log (a); // Array [1, 4, 5, 6, 7, 8]
// 6.Push and pop of the array
// push: is to add the value to the end of the array
        var b = [1,2,3];
        b.push (‘a0’, ‘4’);
        console.log (b); // Array [1, 2, 3, "a0", "4"]

// pop; delete the last element of the array
        b.pop ();
        console.log (b); // Array [1, 2, 3, "a0"]
        // 7. Shift and unshift of the array
        unshift: insert value to the beginning of the array
        shift: delete the first element of the array
        b.unshift (888,555,666);
        console.log (b); // Array [888, 555, 666, 1, 2, 3, "a0"]

        b.shift ();
        console.log (b); // Array [555, 666, 1, 2, 3, "a0"]
// 8.Summarize the array characteristics of js
// Array characteristics in java: specify what type of array, only what type can be loaded. There is only one type.
// Array features in js
// Array features in js 1: Arrays in js can be of any type, without any restrictions.
// Array feature in js 2: Array in js, the length changes with the subscripts. As long as it is used, there is as long as it takes.
    </ script>


Third, the date object (date)

1. Create a date object

     Create a date object
//        method one:
        var now = new Date ();
        console.log (now.toLocaleString ()); // 9/25/2017 6:37:16 PM
        console.log (now.toLocaleDateString ()); // 2017/9/25
// way two
        var now2 = new Date (‘2004/2/3 11:12’);
        console.log (now2.toLocaleString ()); /// 2/3/2004 11:12:00
        var now3 = new Date (‘08 / 02/20 11:12 ’); /// 8/2/2020 11:12:00
        console.log (now3.toLocaleString ());

        // Method 3: The parameter is milliseconds
        var nowd3 = new Date (5000);
        alert (nowd3.toLocaleString ());
        alert (nowd3.toUTCString ()); // Thu, 01 Jan 1970 00:00:05 GMT
2.Date object method-get the date and time

Get date and time
getDate () get date
getDay () Get week
getMonth () get the month (0-11)
getFullYear () Get full year
getYear () get year
getHours () get hours
getMinutes () Get minutes
getSeconds () get seconds
getMilliseconds () Get milliseconds
getTime () returns the cumulative milliseconds (from 1970/1/1 midnight)
Example exercises

1.Print this format 2017-09-25 17:36: Monday

function foo () {
            var date = new Date ();
            var year = date.getFullYear ();
            var month = date.getMonth ();
            var day = date.getDate ();
            var hour = date.getHours ();
            var min = date.getMinutes ();
            var week = date.getDay ();
            console.log (week);
            var arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            console.log (arr [week]);
// console.log (arr [3]);
            console.log (year + ‘-’ + chengemonth (month + 1) + ’-’ + day + ‘‘ + hour + ’:’ + min + ‘:’ + arr [week])
        }
        function chengemonth (num) {
            if (num <10) {
                return ‘0’ + num
            }
            else {
                return num
            }
        }
        foo ()
        console.log (foo ()) // No return value returns undefined

        // Ternary operator
         console.log (2> 1? 2: 1)


2. Set the date and time

// Set the date and time
// setDate (day_of_month) set the day
// setMonth (month) set month
// setFullYear (year) set year
// setHours (hour) set hours
// setMinutes (minute)
// setSeconds (second) set seconds
// setMillliseconds (ms) Set milliseconds (0-999)
// setTime (allms) Set the accumulated milliseconds (from 1970/1/1 midnight)
    
var x = new Date ();
x.setFullYear (1997); // Set the year 1997
x.setMonth (7); // Set month 7
x.setDate (1); // Set day 1
x.setHours (5); // Set hours 5
x.setMinutes (12); // Set minutes 12
x.setSeconds (54); // Set seconds 54
x.setMilliseconds (230); // Set milliseconds 230
document.write (x.toLocaleString () + "<br>");
// Return at 5:12:54 on August 1, 1997

x.setTime (870409430000); // Set cumulative milliseconds
document.write (x.toLocaleString () + "<br>");
// Return at 12:23:50 on August 1, 1997


3.Date and time conversion:

Date and time conversion:

getTimezoneOffset (): 8 time zones × 15 degrees × 4 minutes / degree = 480;
Returns the time difference between local time and GMT, in minutes
toUTCString ()
Returns the international standard time string
toLocalString ()
Returns a local format time string
Date.parse (x)
Returns the cumulative milliseconds (from 1970/1/1 midnight to local time)
Date.UTC (x)
Returns the cumulative milliseconds (from 1970/1/1 midnight to international time)


Fourth, Math objects (mathematical)
// The attribute methods in this object are related to mathematics.
   

a(v.toString ()) // return 11,55, ‘hello’, true, 656,4,5
// 3. Reserve sort
// reserve: inverted array elements
        var li = [1122,33,44,20, ‘aaa’, 2];
        console.log (li, typeof (li)); // Array [1122, 33, 44, 55] object
        console.log (li.toString (), typeof (li.toString ())); // 1122,33,44,55 string
        alert (li.reverse ()); // 2, ‘aaa’, 55,44,33,1122
// sort: sort array elements
        console.log (li.sort (). toString ()); // 1122,2,20,33,44, aaa is sorted by ascii code value
// What if you want to compare by numbers? (Just define a function)
//        method one
        function intsort (a, b) {
            if (a> b) {
                return 1;
            }
            else if (a <b) {
                return -1;
            }
            else {
                return 0;
            }
        }
        li.sort (intsort);
        console.log (li.toString ()); // 2,20,33,44,1122, aaa

// way two
        function Intsort (a, b) {
            return a-b;
        }
        li.sort (intsort);
        console.log (li.toString ());
        // 4.Array slice operation
        //x.slice(start,end);
        var arr1 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’];
        var arr2 = arr1.slice (2,4);
        var arr3 = arr1.slice (4);
        var arr4 = arr1.slice (2, -1);
        alert (arr2.toString ()); // The result is "c, d"
        alert (arr3.toString ()); // The result is "e, f, g, h"
        alert (arr4.toString ()); // The result is "c, d, e, f, g"
// 5.Delete the sub-array
        var a = [1,2,3,4,5,6,7,8];
        a.splice (1,2);
        console.log (a); // Array [1, 4, 5, 6, 7, 8]
// 6.Push and pop of the array
// push: is to add the value to the end of the array
        var b = [1,2,3];
        b.push (‘a0’, ‘4’);
        console.log (b); // Array [1, 2, 3, "a0", "4"]

// pop; delete the last element of the array
        b.pop ();
        console.log (b); // Array [1, 2, 3, "a0"]
        // 7. Shift and unshift of the array
        unshift: insert value to the beginning of the array
        shift: delete the first element of the array
        b.unshift (888,555,666);
        console.log (b); // Array [888, 555, 666, 1, 2, 3, "a0"]

        b.shift ();
        console.log (b); // Array [555, 666, 1, 2, 3, "a0"]
// 8.Summarize the array characteristics of js
// Array characteristics in java: specify what type of array, only what type can be loaded. There is only one type.
// Array features in js
// Array features in js 1: Arrays in js can be of any type, without any restrictions.
// Array feature in js 2: Array in js, the length changes with the subscripts. As long as it is used, there is as long as it takes.
    </ script>


Third, the date object (date)

1. Create a date object

     Create a date object
//        method one:
        var now = new Date ();
        console.log (now.toLocaleString ()); // 9/25/2017 6:37:16 PM
        console.log (now.toLocaleDateString ()); // 2017/9/25
// way two
        var now2 = new Date (‘2004/2/3 11:12’);
        console.log (now2.toLocaleString ()); /// 2/3/2004 11:12:00
        var now3 = new Date (‘08 / 02/20 11:12 ’); /// 8/2/2020 11:12:00
        console.log (now3.toLocaleString ());

        // Method 3: The parameter is milliseconds
        var nowd3 = new Date (5000);
        alert (nowd3.toLocaleString ());
        alert (nowd3.toUTCString ()); // Thu, 01 Jan 1970 00:00:05 GMT
2.Date object method-get the date and time

Get date and time
getDate () get date
getDay () Get week
getMonth () get the month (0-11)
getFullYear () Get full year
getYear () get year
getHours () get hours
getMinutes () Get minutes
getSeconds () get seconds
getMilliseconds () Get milliseconds
getTime () returns the cumulative milliseconds (from 1970/1/1 midnight)
Example exercises

1.Print this format 2017-09-25 17:36: Monday

function foo () {
            var date = new Date ();
            var year = date.getFullYear ();
            var month = date.getMonth ();
            var day = date.getDate ();
            var hour = date.getHours ();
            var min = date.getMinutes ();
            var week = date.getDay ();
            console.log (week);
            var arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            console.log (arr [week]);
// console.log (arr [3]);
            console.log (year + ‘-’ + chengemonth (month + 1) + ’-’ + day + ‘‘ + hour + ’:’ + min + ‘:’ + arr [week])
        }
        function chengemonth (num) {
            if (num <10) {
                return ‘0’ + num
            }
            else {
                return num
            }
        }
        foo ()
        console.log (foo ()) // No return value returns undefined

        // Ternary operator
         console.log (2> 1? 2: 1)


2. Set the date and time

// Set the date and time
// setDate (day_of_month) set the day
// setMonth (month) set month
// setFullYear (year) set year
// setHours (hour) set hours
// setMinutes (minute)
// setSeconds (second) set seconds
// setMillliseconds (ms) Set milliseconds (0-999)
// setTime (allms) Set the accumulated milliseconds (from 1970/1/1 midnight)
    
var x = new Date ();
x.setFullYear (1997); // Set the year 1997
x.setMonth (7); // Set month 7
x.setDate (1); // Set day 1
x.setHours (5); // Set hours 5
x.setMinutes (12); // Set minutes 12
x.setSeconds (54); // Set seconds 54
x.setMilliseconds (230); // Set milliseconds 230
document.write (x.toLocaleString () + "<br>");
// Return at 5:12:54 on August 1, 1997

x.setTime (870409430000); // Set cumulative milliseconds
document.write (x.toLocaleString () + "<br>");
// Return at 12:23:50 on August 1, 1997


3.Date and time conversion:

Date and time conversion:

getTimezoneOffset (): 8 time zones × 15 degrees × 4 minutes / degree = 480;
Returns the time difference between local time and GMT, in minutes
toUTCString ()
Returns the international standard time string
toLocalString ()
Returns a local format time string
Date.parse (x)
Returns the cumulative milliseconds (from 1970/1/1 midnight to local time)
Date.UTC (x)
Returns the cumulative milliseconds (from 1970/1/1 midnight to international time)


Fourth, Math objects (mathematical)
// The attribute methods in this object are related to mathematics.
   

a...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.