pink teacher js basic self-study notes 02 ECMAScript

object

1, Methods for creating objects

1. Create object {} using object literal

>  -   // var obj = {} / / an empty object is created
>     var obj = {
>       uname: 'xx',
>       age: 18,
>       sex: '',
>       sayHi:function(){
>         console.log('hi~')
>       }
>     }
>     // (1.) the attributes or methods in the form of key value pairs. Key attribute name: value attribute value
>     // (2.) multiple attributes or methods should be separated by
>     // (3.) the method colon is followed by an anonymous function
>     // 2. Object of use
>     // (1) Call the properties of the object. We take the object name. Property name
>     console.log(obj.uname);
>     //  (2) There is also a method object name ['property name'] for calling properties
>     console.log(obj['age']);
>     //  (3) Call the method of the object sayHi object name. Method name () do not forget to add parentheses
>     obj.sayHi();`

2. Create an object using new Object

 // Creating objects with new objects
    var obj = new Object();//An empty object was created
    obj.uname = 'Zhang flash lamp';
    obj.age = 18;
    obj.sayHi = function(){
      console.log('hi~~');
    }

    // (1) We use the equal sign = assignment method to add the properties and methods of the object
    // (2) Each property and method ends with a semicolon

3. Create objects using constructors

 //  Use the method of function to create the same code repeatedly
    // The constructor abstracts some of the same properties and methods in the object and encapsulates them into the function
    
    // Creating objects with constructors
    // Create the same attributes of the objects of the four heavenly kings: name, age, gender and the same method
    //Format:
    // function constructor name (){
    //   this. Attribute = value;
    //   this. Method = function() {}
    // }
    // //Call
    // new constructor name ();

    function Star(uname,age,sex){
      this.name = uname;
      this.age = age;
      this.sex = sex;
      this.sing = function(sang){
        console.log(sang);
      }
    }  
    var ldh = new Star('Lau Andy',18,'male');  //The calling function returns an object
    console.log(ldh.name);
    console.log(ldh['sex']);
    ldh.sing('Ice rain');
    var zxy = new Star('Xue You Zhang',19,'male');
    console.log(zxy.name);
    console.log(zxy['age']);
    zxy.sing('Li Chunlan');

be careful!

1. Constructor names should be capitalized
2. The constructor does not need return to return the result
3. We must use new when calling the constructor
4. As soon as we call the function new Star(), we create an object
5. We must add this before our properties and methods

2, new keyword

Execution process of new keyword

  • The new constructor creates an empty object in memory
  • this will point to the empty object just created
  • Execute the code in the constructor to add properties and methods to the empty object
  • Return this object

3, Traversal object

  • for...in...
// Traversal object
    var obj = {
      name:'ly',
      age:20,
      sex:'female',
      fn:function(){
        console.log('cc')
      }
    }

    // for in traversal object
    // for (variable in object)
    for (var k in obj){
      console.log(k);  //The k variable outputs the attribute names name,age,sex, fn
      console.log(obj[k]); 
      //obj[k] outputs the attribute value ly,20, female, ƒ () {console.log('cc)}
     console.log(obj);
     //The output is {name: 'ly', age: 20, sex: 'female', fn: ƒ}
    }
    

4, Built in object

  • Built in objects are some of the built-in objects of JS language. These objects are used by developers and provide a common or most basic and necessary function (properties and methods)
  • Objects are divided into three types: built-in objects, custom objects, and browser objects

1.Math object

// Math Math object is not a constructor, so we don't need new to call, but just use the properties and methods inside
        console.log(Math.PI); // An attribute pi
        console.log(Math.max(1, 99, 3)); // 99
        console.log(Math.max(-1, -10)); // -1
        console.log(Math.max(1, 99, 'pink teacher')); // NaN
        console.log(Math.max()); // -Infinity
		// 1. Absolute value method
        console.log(Math.abs(1)); // 1
        console.log(Math.abs(-1)); // 1
        console.log(Math.abs('-1')); // Implicit conversion converts string - 1 to number
        console.log(Math.abs('pink')); // NaN 

        // 2. Three rounding methods
        // (1) Math.floor() rounded the floor down to the minimum
        console.log(Math.floor(1.1)); // 1
        console.log(Math.floor(1.9)); // 1
        // (2) Math. Ceil() ceil ceiling rounded up to the maximum value
        console.log(Math.ceil(1.1)); // 2
        console.log(Math.ceil(1.9)); // 2
        // (3) Math.round() is rounded. All other numbers are rounded, but. 5 is special. It takes the larger one  
        console.log(Math.round(1.1)); // 1
        console.log(Math.round(1.5)); // 2
        console.log(Math.round(1.9)); // 2
        console.log(Math.round(-1.1)); // -1
        console.log(Math.round(-1.5)); // The result is - 1
	// 1.Math.random returns a random decimal 0 < = x < = 1
    // 2. This method is not followed by parameters
    // 3. Code verification
    console.log(Math.random());
	 // 4. You want to get a random integer between two numbers and include these two integers
    function getRandom(max, min) {
      return (Math.floor(Math.random() * (max - min + 1)) + min)
    }
    console.log(getRandom(3, 8));
    
	// Random roll call
    var arr = ['cc', 'dd', 'll', 'yy', 'hh'];
    console.log(arr[getRandom(0, arr.length - 1)]);

2.Date() Date object

  • Date() needs to be instantiated to write new
  // Date() needs to be instantiated to write new
    var today = new Date();
    console.log(today);
  • Parameters of the Date() constructor

If Date() does not write parameters, it returns the current time
If Date() writes a parameter, it returns the time entered in parentheses

  • Date formatting
// getFullYear 
    var date = new Date();
    console.log(date.getFullYear());  //Return year 2021
    console.log(date.getMonth() + 1);  //Return to the month, but remember + 1 for the smaller month 
    console.log(date.getDate());     //What number is returned
    console.log(date.getDay());      //Returns Monday to Sunday. Monday is 1 and Sunday is 0

    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var dates = date.getDate();
    var arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
    var day = date.getDay();
    console.log('Today is' + year + 'year' + month + 'month' + dates + 'day' + arr[day]);


       // Hour, minute and second demo: it is required to encapsulate a function to return the current hour, minute and second
    function getTime() {
      var time = new Date();
      var h = time.getHours();//Time
      h = h < 10 ? '0' + h : h;
      var m = time.getMinutes();//branch
      m = m < 10 ? '0' + m : m;
      var s = time.getSeconds();//second
      s = s < 10 ? '0' + s : s;

      return h + ':' + m + ':' + s
    }
    console.log(getTime());
  • Total number of milliseconds (timestamp) to get the date
  • Not the current number of milliseconds, but how many milliseconds have passed since January 1, 1970
  // 1. Use valueof() gettime()
    var date = new Date();
    console.log(date.valueOf());
    console.log(date.getTime());

	//2. Simple writing
	var date1 = +new Date();   //+new Date() returns the number of milliseconds
	console.log(date1);

	// 3. There is a compatibility problem with the total milliseconds obtained in H5
	console.log(Date.now());

5, Array

1. Create array

 var arr = [1,2,3];
    console.log(arr[2]);
    // var arr = new Array(2); / / here 2 is the length of the array
    var arr1 = new Array(1,2); //Equivalent to [1,2] has two array elements
    console.log(arr1);

2. Check whether it is an array

 // Detect whether it is an array
    // 1. instanceof operator, which can detect whether it is an array
    var arr = [];
    var obj = {};
    console.log(arr instanceof Array);  //true 
    console.log(obj instanceof Array);  //false
    // 2. Array.isarray (parameter); H5 add method IE9 above
    console.log(Array.isArray(arr))   //true
    console.log(Array.isArray(obj))   //false

3. Array de duplication

 // Array de duplication
    //Idea: first traverse the old array, and then take the elements of the old array to query the new array. If the element is not in the new array, it will be added, otherwise it will not be added
    // How do you know if an element exists? Use the new array. Indexof (array element). If - 1 is returned, it means that there is no element in the new array
    // Old array ['c','a','z','a','x','a','x','c','b ']
    // Encapsulate a de duplication function unique 
    function unique(arr){
      var newArray = [];
      for (var i = 0; i < arr.length; i++) {
        if (newArray.indexOf(arr[i]) === -1){
          newArray.push(arr[i]);
        }
      }
      return newArray;
    }
    var demo = unique(['c','a','z','a','x','a','x','c','b'])
    console.log(demo);

4. Basic package type

  • Basic wrapper types wrap simple data types into complex data types, so that simple data types have properties and methods
	var str = 'hello';
    console.log(str.length);

    // amount to
    var temp = new String('hello');
    // Assign temp to str
    var str = temp;
    // Release temp
    temp = null;
    console.log(str.length);

	// The string object returns the position str.indexOf('character to find ', [starting position]) according to the character
	var str = 'Spring is coming, spring is coming';
	console.log(str.indexOf('spring')); //0
	console.log(str.indexOf('spring',[3])); //5 at the index value position
  • Find the position and number of occurrences of o in the string 'abcoefoxyozzopp'
 //1. Find the position of the first o first
// Then, if the result returned by indexOf is not - 1, continue to look for it later
// Since indexOf can only find the first one, the following search must be the current index value + 1 to continue the search
	var str = 'abcoefoxyozzopp';
	var index = str.indexOf('o');
	var t = 0;
	while (index != -1) {
	  console.log(index);
	  t++;
	  index = str.indexOf('o',index + 1);
	}
	console.log('o The number of occurrences is'+ t);
  • Return value according to position
// Return value according to position
// 1. charAt(index) returns characters based on position
var str = 'andy';
console.log(str.charAt(3));//y
// Traversal character
for (var i = 0; i < str.length; i++) {
  console.log(str.charAt(i));
  
}
// //2.charCodeAt(index) returns the ASCII value of the corresponding index number character. Purpose: to judge which key the user pressed
console.log(str.charCodeAt(0)); //97

// 3. STR [index] H5 NEW
console.log(str[0]);  //a

  • Judge whether the attribute object [attribute] exists in the object
var o = {
  age :19
}
if (o['age']) {
  console.log('There is this attribute in it');
} else {
  console.log('There is no such attribute');
}
  • Judge the character that appears the most times in the string 'abcoeo fox yo zzopp' and count its times
  //Core algorithm: use charAt() to traverse this string
  // (1) Store each character to the object. If the object does not have this attribute, it will be 1. If it exists, leave + 1
  // Traverse the object to get the maximum value and the character
	var str = 'abcoeofoxyozzopp';
	  var o = {};
	  for (var i = 0; i < str.length; i++) {
	    var chars = str.charAt(i); //chars is each character of the string
	    if (o[chars]) {  //o[chars] gets the attribute value
	      o[chars]++;
	    }else{
	      o[chars] = 1;
	    }
	    
	  }
	  console.log(o);
	  //(2) Traversal object
	  var max  = 0;
	  var ch = '';
	  for (var k in o) {
	    // k gets the attribute name
	    // o[k] gets the attribute value
	    if (o[k]>max) {
	      max = o[k];
	      ch = k;
	    }
	  }
	  console.log(max);
	  console.log('The maximum number of characters is'+ch);

6, Simple and complex types

  • Simple type: basic data type (value type)

Value type: simple data type / basic data type. During storage, the value itself is stored in the variable, so it is called value type: String, number, Boolean, undefined, null. Simple data types are in the stack, which directly opens up space and stores values

  • Complex types: reference types

Reference type: complex data type. When stored, only the address (Reference) is stored in the variable, so it is called reference data type. Objects (system objects, user-defined objects) created through the new keyword, such as Object, Array, Date, etc. For complex types in the heap, first store the address in the stack, which is represented in hexadecimal. The address points to the data in the heap

 // The simple data type null returns an empty object object
    var timer = null;
    console.log(typeof(timer)); //object
    // If you plan to store a variable as an object in the future, you can save it as null first

    // Object arrays are complex data types

1. Simple type and complex type parameters

	 // Simple type parameters
	    function fn(a){
	      a++;
	      console.log(a);  //11
	    }
	    var x = 10;
	    fn(x);
	    console.log(x); //10
    
	 // Complex type parameters
	    function Person(name){
	      this.name = name;
	    }
	    
	    var p = new Person('Lau Andy');
	    console.log(p.name); //Lau Andy
	  

Tags: Javascript Front-end ECMAScript

Posted on Mon, 25 Oct 2021 21:32:59 -0400 by Will Poulson