JavaScript Basics – objects

Time:2022-5-29

Introduction

JavaScript Basics - objects

Object definition Png

Object basis

create object

Create objects with literals:

Var obj = {}// Created an empty object
        var obj1 = {
            name: 'Omew',
            age: 18,
            sex: 'female',
            Sayhi: function() {// only anonymous functions can be used here
                console.log('Hello~');
            }
        }

Working with objects

        console.log(obj1.name);    //  Omew
        console.log(obj1.age);      //  18
        console.log(obj1['sex']);    //   female
        obj1.sayHi();                     //   Hello~

Creating objects with new object

Var obj2 = new object()// Created an empty object
        Obj2.uname ='kana', // add attribute
        obj2.uage = 16,
        obj2.sex = 'female',
        Obj2.greeting = function() {// append method
                 console.log('Domo~');
             }

Use objects in exactly the same way as above

Creating objects with constructors
This method can create multiple objects at once
Constructor is to abstract some of the same attributes and code in an object and encapsulate them in a function

Function star (uname, age, sex) {// constructor name is capitalized
            this.uname = uname;
            this.age = age;
            This Sex = sex// Constructor can return results without return
            this.sing = function (song) {
                console.log(song);
            }
        }
        
        Var star1 = new star ('liu', 18,'male')// Call constructor (must use new keyword) to create object
        console.log(typeof star1);    // Object
        console.log(star1.uname);      // Liu
        console.log(star1['age']);     // 18
        star1.sing('Rain...')

        var star2 = new Star('Zhang',19,'male');
        console.log(star2.uname);

Relationship between constructor and object:

JavaScript Basics - objects

The relationship between constructor and object Png

Execution process of new keyword:

  1. Create a new empty object in memory;
  2. Let this point to the new object;
  3. Execute the code in the constructor to add properties and methods to the new object;
  4. Return the new object (so return is not required in the constructor)

How to traverse an object?

//Traversal of objects
        //The internal properties of the object are unordered, so it is impossible to traverse with the traditional for loop
        // for in
        for (var k in obj1){
            Console Log (k)// Traversal property name
            Console Log (obj1[k])// Traverse attribute values
        }

Built in objects:

JavaScript Basics - objects

Built in objects Png

In general, it is recommended to consult mdn/w3c documents

Built in objects: Math

Math object (non constructor, can be used directly without calling new keyword)

Console Log (math.pi)// Built in object properties, PI
        Console Log (math.max (1,5,6,8,4,3))// Built in object method, Max
        Console Log (math.abs (-56))// absolute value

Math built in rounding method

Console Log (math.floor (1.1))// Integer down
        console.log(Math.floor(1.9));

        Console Log (math.ceil (1.2))// Upward evidence collection

        Console Log (math.round (1.5))// Rounding

Math built in random function

//Math Random() returns a random floating-point number in the range [0,1)
        console.log(Math.random());

Returns a random integer within an interval, including the boundary

        function getRandomNumber(min,max) {
            return Math.floor(Math.random() * (max - min + 1)) + min
        }
        console.log(getRandomNumber(1,100));

Built in objects: Date

Date object (Date object can only be created by calling the date constructor)

Var arr = new array()// Several object types that must use the new keyword
        var obj = new Object();
        Var day = new date()// If there is no parameter, the current time is output
        console.log(day);       //    "2021-10-19T03:44:00.755Z"

Add parameters to date()

Var Day1 = new date (2021,5,1)// The actual output is June, because the month count starts from 0
        console.log(day1);         //  "2021-05-31T16:00:00.000Z"
        var day2 = new Date('2021-5-1 8:8:8')
        console.log(day2);         //   "2021-05-01T00:08:08.000Z"

Date formatting

Console Log (day.getfullyear())// Returns the current year
        Console Log (day.getmonth() + 1)// Return current month (0-november)
        Console Log (day.getdate())// What number to return
        Console Log (day.getday())// Returns the day of the week (Sunday is 0)
        console.log(`Today is ${day.getFullYear()}.${day.getMonth() + 1}.${day.getDate()}`);

Time formatting

console.log(day.getHours());
        console.log(day.getMinutes());
        console.log(day.getSeconds());
        Function gettime() {// time format encapsulation function
            var h = day.getHours();
            h = h < 10 ? '0' + h : h;
            var m = day.getMinutes();
            m = m < 10 ? '0' + m : m;
            var s = day.getSeconds();
            s = s < 10 ? '0' + s : s;
            var time = `${h}:${m}:${s}`
            return time;
        }

        console.log(getTime());

Total number of milliseconds (timestamp) to get the date
The starting time of computer prefabrication is January 1st, 1970

Console Log (day.valueof())// Returns the number of milliseconds from January 1, 1970
        Console Log (day.gettime())// Ibid

Simple:

        var  date1 = +new Date();
        console.log(date1);

Or directly:

Console Log (date.now())// H5 new method

Countdown case
The countdown cannot be directly subtracted from the displayed time
Here, the time stamp is used to subtract the remaining time milliseconds
Then convert the number of milliseconds to the displayed time format

function countDown(time) {
            Var nowtime = +new date()// Returns the timestamp of the current time
            Var deadline = +new date (time)// Returns the timestamp of the specified time
            Var times = (deadline - nowtime) / 1000// Time is the timestamp of the remaining time in seconds

            var min = parseInt(times / 60 % 60);
            min = min < 10 ? '0' + min : min;
            var hour = parseInt(times / 60 / 60 % 24);
            hour = hour < 10 ? '0' + hour : hour;
            var day = parseInt(times / 60 / 60 / 24);
            var sec = parseInt(times % 60);
            sec = sec < 10 ? '0' + sec : sec;

            var countTime = `${day}day  ${hour}:${min}:${sec}`;
            return countTime;

        }

        console.log(countDown('2022-1-1 00:00:00'));

Built in objects: arrays

Array object

Var arr = []// Create an empty array using array literals
        Var Arr1 = new array (3)// The created array is still an empty array with 3 empty array elements
        console.log(arr1);
        var arr2 = new Array(1,2,3);  
        console.log(arr2);   // [1,2,3]

Detect whether it is an array

Using the instanceof operator

        console.log(arr1 instanceof Array);   // true
        console.log(arr instanceof Array);    // true
        var obj = new Object;
        console.log(obj instanceof Array);    // false

Using the built-in method array Isarray() supported by versions above IE9

        console.log(Array.isArray(arr1));    // true

Add or remove array elements

Push() appends elements to the end of the array

Console Log (arr2.push (4,'apple'))// After the push() operation is completed, the new array length will be returned
        console.log(arr2);

Unshift() appends an element at the beginning of the array

        console.log(arr2.unshift('head',0));
        console.log(arr2);

Pop() deletes an element at the end of the array

var arr3 = arr2;
        Console Log (arr3.pop())// After the pop() operation is completed, a value will also be returned. The returned value is the deleted element
        console.log(arr3);

Shift() deletes the first element of the array

        console.log(arr3.shift());
        console.log(arr3);

Flip array

        console.log(arr3.reverse());

sort

        var arr4 = [3, 7, 5, 9, 6, 2, 1]
        arr4.sort();
        console.log(arr4);    //   1,2,3,5,6,7,9

When the array contains elements with more than two digits, only using sort() will not give you the desired results:

        var arr5 = [1, 15, 6, 8, 22, 54, 5, 9, 96, 72]
        console.log(arr5.sort());   //  [1, 15, 22, 5, 54, 6, 72, 8, 9, 96]

The reason for this is that sort() only sorts by the size of the first character
If you want to sort by value size, you can do this:

arr5.sort(function (a, b) {
            Return a - B// Ascending sort
            //Return B - A; Descending sort
        });
        console.log(arr5);

Return array element index number

If there are the same elements in the array, the index number of the first element is returned
If there is no corresponding element in the array, -1 is returned

        var colors = ['red', 'blue', 'yellow', 'green'];
        console.log(colors.indexOf('yellow'));   // 2
        console.log(colors.indexOf('black'));   // -1  

Similarly, the index number of the array element is returned. The difference is to search from the back to the front

        console.log(colors.lastIndexOf('green'));    // 4

Instance, array de duplication

Algorithm: traverse the old array, get the elements of the old array and query in the new array. If the elements do not appear in the new array, add them. Otherwise, do not add them

        function uniqueArr(arr) {
            var newArr = [];
            for(var i = 0; i < arr.length; i++){
                if (newArr.indexOf(arr[i]) == -1){
                    newArr.push(arr[i]);
                }
            }
            return newArr;
        }

        var demo = ['a', 'z', 'h', 'z', 'b', 'a', 'k', 'z', 'h'];
        console.log(uniqueArr(demo));    // ["a", "z", "h", "b", "k"]

Instance, array converted to string

        var arr = [1, 2, 3];
        console.log(arr.toString());  // 1,2,3

        var arr1 = ['apple', 'orange', 'banana'];
        console.log(arr1.join());    // apple,orange,banana
        console.log(arr1.join(' & '));   // apple & orange & banana

Built in objects: strings

String object

Return position by character

var str = 'this is a para but contain nothing interesting...'
        console.log(str.indexOf('s'));   // 3 
                                                       //Returns only the first occurrence of the character

Indexof() can add the second parameter as the starting position, that is, to start searching from the given starting position

        console.log(str.indexOf('s', 4));    // 6

Similarly, there is also the lastIndexOf () method, which can be searched from the back to the front. It will not be repeated here

Instance to find the position and number of repetitions of a character in a string

Algorithm: first find the position of the first string
As long as the value of indexof() is not -1, continue to search
The indexof () method can only find one element, so after each search, you should continue to search from the current index + 1 position

        function  getSameChara(str,le) {
            var index = str.indexOf(le);
            var num = 0;
            var arr = [];
            while(index != -1){
                arr.push(index);
                num++;
                index = str.indexOf(le,index + 1);
            }
            return [arr,num]
        }

        console.log(getSameChara(str,'i'));

Returns characters based on index position

Charat() method returns characters

        var str = 'omewspg'
        console.log(str.charAt(5));   // p

Traverse all characters

        var arr1 = [];
        for(i = 0; i < str.length; i++){
            arr1.push(str.charAt(i));
        }
        console.log(arr1);     // ["o", "m", "e", "w", "s", "p", "g"]

The charcodeat() method returns the character ASCII code

        console.log(str.charCodeAt(5));   // 112

Str[index] H5 new method, also used to return characters

        console.log(str[5]);   // p

Instance to count the characters with the most occurrences

Algorithm: use charat() to traverse the string
Each character saved in the string is stored as an attribute of the object. If the repeated string is traversed, the attribute +1
Traverse the object to get the attribute with the largest attribute value and the character

var str = 'this is a para but contain nothing interesting...'
        var obj = {};
        for (var i = 0; i < str.length; i++){
            var chars = str.charAt(i);
            If (obj[chars]) {// attributes are appended through brackets + variables. Dot notation cannot do this
                obj[chars] ++;
            }else{
                obj[chars] = 1;
            }
        }
        console.log(obj);
        //Traversal object
        var max = 0;
        var ch = '';
        for(var k in obj){
            if(obj[k] > max){
                max = obj[k];
                ch = k;
            }
        }
        console.log(max);
        console.log(ch);

String operation method

Splicing

var str1 = 'omew';
        Console Log (str1.concat ('spg'))// Effect similar to + sign

Interception

var str2 = 'this is a para...'
        Console Log (str2.substr (5,2))// The first parameter represents the starting index number; The second parameter indicates how many characters to take

        Console Log (str2.slice (5,7))// The first parameter represents the starting index number; The second parameter represents the closing index number (the corresponding character of the index cannot be obtained)
                                        //The output of the above two examples is

replace

Console Log (str2.replace ('para','apple')// Replace the first para character with apple

If you need to replace all the same characters, you can use the loop operation

        while(str2.indexOf('a') !== -1){
            str2 = str2.replace('a','*');
        }
        console.log(str2);

String to array split() (array to string join)

        var str3 = 'car&plane&boat'
        console.log(str3.split('&'));    // ["car", "plane", "boat"]

Immutability of strings

JavaScript Basics - objects

Immutability of strings Png

Recommended Today

Simple implementation of bucket sort

1 #include 2 3 int main() 4 { 5 // Simplified bucket sort 6 int a[101],i,j,num,t; 7 for(i=0;i<=100;i++) 8 a[i]=0; //initialize to 0 9 printf(&quot;Enter the number of digits:&quot;); 10 scanf(“%d”,&num); 11 12 for(i=1;i<=num;i++) 13 { 14 scanf(&quot;%d&quot;,&amp;t);//Assign numbers to the corresponding array 15 a[t]++;//The elements in the array represent the number of numbers 16 […]