Section 19: packaged objects and built-in objects

Posted by rigy73 on Wed, 19 Jan 2022 11:39:13 +0100

1. Packaging object

Why can underlying types use properties or methods?
In JS, although only objects have properties and methods, the basic data type can also call methods. This is because the JS interpreter will judge whether the previous thing is an object when it encounters a point or square bracket. If it is executed directly, if not, it means it is a basic data type, and the interpreter will create an object corresponding to the basic type, Let the user access the property or method corresponding to the object. When the property access or method execution is completed, the object will be deleted immediately, so the basic data type can also use the method.
Wrapper object: an object created at the same time as the call is called a wrapper object.
The process of calling method for basic data type: create wrapper object - call method - delete wrapper object
Number, string, Boolean wrapped object
null and undefined have no wrapper object, so calling methods and properties will report an error

var v1 = new Number(123);
var v2 = new String('abc');
var v3 = new Boolean(true);

typeof v1 // "object"
typeof v2 // "object"
typeof v3 // "object"
new Number(123).valueOf()  // 123
new String('abc').valueOf() // "abc"
new Boolean(true).valueOf() // true
var num,str,boo;
num=1234;
str='abcd';
boo=true;
num.length;//undefined
str.length;//4
boo.length;//undefined
null.len;//Error Cannot read properties of null (reading 'length')
//Interview question packaging object pit
var str='abc';
str.length = 4;//The packaging object created after assignment is completed is directly destroyed after creation
str.length;//Still 3

Note: the wrapper object is created during the call and deleted after the call
Objects have two basic methods valueOf() and toString(), so the wrapper object also has these two methods.
① Boolean type
Only these two methods are available for Boolean types, which are not very useful in practical development.

new Boolean(true).valueOf();//true
new Boolean(false).valueOf();//false
new Boolean(false).toString();//'false'
new Boolean(true).toString();//'true'

② Number type
In addition to these two methods, numeric types can also call toFixed(), toExponential(), toPrecision()

methodusagegrammar
toFixed()Rounds Number to the specified Number of decimal placesNumberObject.toFixed(num); Num specifies the number of decimal places, which is a value between 0 and 20, including 0 and 20. Some implementations can support a larger range of values. If this parameter is omitted, it will be replaced by 0
toExponential()The value of an object can be converted into an exponential counting methodNumberObject.toExponential(num); Num specifies the number of decimal places in the exponential counting method, which is a value between 0 and 20, including 0 and 20. Some implementations can support a larger range of values. If this parameter is omitted, as many numbers as possible are used
toPrecision()Object is converted to exponential counting when its value exceeds the specified number of digitsumberObject.toPrecision(num) ; Num specifies the minimum number of digits that must be converted to exponential counting. This parameter is a value between 1 and 21 (including 1 and 21). Effective implementation allows for selectively supporting larger or smaller num. If this parameter is omitted, the method toString() is called instead of converting numbers to decimal values

toFixed() note:
——Reserve 20 digits at most, and an error will be reported if it exceeds 20;
——Normal browsers use rounding. The earliest ie6 or ie7 may be different. If you want to be compatible, you can encapsulate the method of keeping decimals yourself
——The result is of type string

new Number(123).valueOf(); //Result: number 123
new Number(123).toString();//Result: String '123'
var num=123;
num.valueOf();//123
num.toString();//'123'
num.toFixed(2);//Result: two decimal places are reserved, and the data type is string '123.00'
var num = 15200000000000;
num.toExponential();//'1.52e+13'
num.toExponential(0);//Keep 0 decimal places' 2e+13 '
num.toPrecision();Convert directly to string '15200000000000'
num.toPrecision(8);//Exceeding 8 bits is represented by index '1.5200000e+13'
//The toFixed and toExponential parameters represent the number of decimal places to be retained, and the toPrecision parameter represents the total number of decimal places

③ String type

  • The charAt() method returns the character stringobject at the specified position charAt(index)
  • charCodeAt() returns the Unicode encoding of the character at the specified position. Syntax: stringobject charCodeAt(index)
  • concat() connects strings. Generally, this method is not used. The common method is string splicing with the + sign. Stringobject concat(stringX,stringX,…,stringX)
  • indexOf() retrieve String Syntax: stringobject indexOf(searchvalue,fromindex)
    searchvalue retrieves the string. Where does fromindex start? formindex can be omitted. If omitted, it starts from 0. If there is any, it returns the position where the search character first appears. If not, it returns - 1
  • lastIndexOf() searches the string from back to front, just like the indexOf parameter, except that the search method searches from back to front
  • split() divides a string into an array of strings. Syntax: stringobject split(separator,howmany),
    Separator partition ID, howmany returns the length limit of the array, each character is separated, and separator is set to empty string ''
  • slice() extracts the fragment of the string and returns the extracted part in the new string. Syntax: stringobject Slice (start, end), including start but not end
  • substr() extracts the specified number of characters from the string from the starting index number. Syntax: stringobject substr(start,length)
  • substring() extracts the characters between two specified index numbers in a string. Syntax: stringobject substring(start,stop)
  • Tolowercase() converts the string to lowercase. Syntax: stringobject toLowerCase()
  • Touppercase() converts the string to uppercase. Syntax: stringobject toUpperCase()
  • trim() clears spaces before and after
  • trimLeft() clears the left space
  • Trimlight() clears the space on the right

These are es5 available methods

'hello word'.charAt(2);//Returns the character at subscript 2, starting with 0
'hello word'.charCodeAt(2);//108
'leo'.concat(' is a boy');//'leo is a boy'
'leo'.concat(' is',' a',' boy');//'leo if a boy'
'hello'+' word';//'hello word'
'abcd'.split('');//(4) ['a', 'b', 'c', 'd']
'abcd'.split('',2);//Set the return array length to 2 (2) ['a ',' B ']
'abcd'.split('b');//(2) ['a', 'cd']
//slice(),substr(),substring()
'abcdefghijklmb'.slice(2,4);//Intercept from 2 to 4, including 2 but not 4'cd '
'abcdefghijklmb'.slice(1,5);//'bcde'
'abcdefghijklmb'.substr(1,1);//Starting from 1, intercept 1 'b'
'abcdefghijklmb'.substr(1,3);//Starting from 1, intercept 3 'bcd'
'abcdefghijklmb'.substring(1,5);//From 1 to 5, including 1 and excluding 5 'bcde'

The difference between slice() and substring():
▶ When the second parameter is less than the first parameter, substring will transfer the two parameters; slice does not rotate, but returns an empty string
▶ If a negative number is passed in, substring will be treated as 0 and slice will be treated as the penultimate bit
Differences between substr():
▶ substr the second represents the length, not the subscript position
▶ Because the second represents the length, the second negative number will not be reversed
▶ If the first number is negative, it indicates the penultimate digit

'abcdefghijklmb'.slice(5,1);//''
'abcdefghijklmb'.substring(5,1);//'bcde'
'abcdefghijklmb'.slice(5,-2);//'fghijkl'
'abcdefghijklmb'.substring(2,-1);//'ab'
'abcdefghijklmb'.substr(-2,1);//'m'
'abcdefghijklmb'.substr(2,-1);//''

Three methods, trim(), trimLeft(), and trimlight(), have no parameters

'  abc  defghijklmb  '.trim();//'abc  defghijklmb'
'  abc  defghijklmb  '.trimLeft();//'abc  defghijklmb  '
'  abc  defghijklmb  '.trimRight();//'  abc  defghijklmb'

Methods that may be used in es6

  • The padStart() string is not enough to complete the specified length. Two parameters are accepted. The first parameter is the maximum length of string completion, and the second parameter is the string used for completion
  • padEnd() string is not long enough. The tail is complete
  • includes(): returns a Boolean value indicating whether a parameter string was found.
  • startsWith(): returns a Boolean value indicating whether the parameter string is at the head of the original string.
  • endsWith(): returns a Boolean value indicating whether the parameter string is at the end of the original string
  • The repeat() method returns a new string, indicating that the original string is repeated n times
//If the length of the original string is equal to or greater than the maximum length, the string completion will not take effect and the original string will be returned
'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'
//If the sum of the length of the complement string and the original string exceeds the maximum length, the complement string exceeding the digits will be truncated
'abc'.padStart(10, '0123456789')// '0123456abc'
//If the second parameter is omitted, the default is to use spaces to complete the length
'x'.padStart(4) // '   x'
'x'.padEnd(4) // 'x   '
//A common use is to specify the number of digits for numeric completion
'1'.padStart(10, '0') // "0000000001"
'12'.padStart(10, '0') // "0000000012"
'123456'.padStart(10, '0') // "0000123456"
//Prompt string format
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"

padStart() and padEnd() method references
includes(), startsWith(), endsWith() is used to determine whether a string is included in another string; The first parameter represents the search string, and both support the second parameter, indicating the location where to start the search

let s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
//If the parameter is negative or Infinity, an error will be reported
'na'.repeat(Infinity)// RangeError
'na'.repeat(-1)// RangeError
//If the parameter is a decimal between 0 and - 1, it is equivalent to 0
'na'.repeat(-0.9) // ""
//Parameter NaN is equal to 0
'na'.repeat(NaN) // ""
//If the parameter of repeat is a string, it will be converted to a number first
'na'.repeat('na') // ""
'na'.repeat('3') // "nanana"

String method example:
String flip

var x='hello word';
x.split('').reverse().join('');//'drow olleh'

What day is today

var d = new Date().getDay();//Get the number corresponding to the week, 6
var nowWeek='Today is Sunday' + 'Day one two three four five six'.charAt(d);
nowWeek; //'today is Saturday '

HTML object for string

var a='abcd';
console.log(a.big());//<big>abcd</big>
console.log(a.fontcolor('#f00'));//<font color="#f00">abcd</font>
console.log(a.bold());//<b>abcd</b>
...

Enter a point (a.) on the browser console to find the corresponding method
String regularization method
search() search, match() match, replace() replace
Detailed explanation on regular

2. Built in object

Single built-in object, referred to as built-in object for short;
Built in objects do not need to be instantiated with the new operator;
The instantiation and construction methods of new operator are explained in detail in the next section;
There are only two real built-in objects in JS that do not need to be instantiated with the new operator: global object and math object

First: global object

In different environments, the expression is also different
In the browser environment, the global object is actually a window object, which is more accurately a part of the window object.

Common properties and methods of global objects:
① Methods for handling numbers: isfinish(), isNaN(), parseFloat(), parseInt()

  • Isfinish() checks whether a value is a finite number.
  • isNaN() checks whether a value is a number.
  • parseFloat() parses a string and returns a floating point number.
  • parseInt() parses a string and returns an integer.
    ② Method of processing URI
  • decodeURI() decodes an encoded URI.
  • decodeURIComponent() decodes an encoded URI component.
  • encodeURI() encodes a string as a URI. (all characters will not be encoded, such as?! will not be processed)
  • encodeURIComponent() encodes the string as a URI component (encoding all special characters)
  • escape() encodes the string. (abandoned)
  • unescape() decodes the string encoded by escape(). (abandoned)
var x='https://editor.csdn.net/md?articleId=121979276';
encodeURIComponent(x);//'https%3A%2F%2Feditor.csdn.net%2Fmd%3FarticleId%3D121979276'
encodeURI(x);//'https://editor.csdn.net/md?articleId=121979276'

③ Another: eval() evaluates the JavaScript string and executes it as script code.
The eval() method receives a string and can execute the string as an idiom sentence;

eval("2+2");//4
eval("console.log(11111)");//11111
//Common usage 1: convert JSON string objects into objects. Use in lower versions. Use JSON objects in higher versions. JSON is a es5 new object
var str='{"yzId":4083,"yzCode":"282123654","yzName":"test","yzlxId":1,"deptId":100,"deptName":"Management Center","areaId":-1}';
eval('('+str+')');
eval('({"yzId":4083,"yzCode":"282123654","yzName":"test","yzlxId":1,"deptId":100,"deptName":"Management Center","areaId":-1})');
//Common 2: dynamic declaration variables

Why add ()?
The reason lies in the problem of eval itself. Because json starts and ends with "{}", it will be treated as a statement block in JS, so it must be forcibly converted into an expression

eval('{}');//undefined
eval('({})');//{}

eval problem
When eval declares that there is no variable promotion for the variable, it will be created when eval is executed;
Variables defined by eval in strict mode cannot be accessed outside eval;
Unable to use debugging tools for debugging;
Very affect performance;
There are potential safety hazards;

global properties

Most global attributes are constructors, such as number, function and error. Only three attributes are special values: undefined, NaN and infinity

global.undefined;//undefined
global.NaN;//NaN
global.Infinity;//Infinity
global.undefined === window.undefined;//true

Second: math object

math object reference manual
Possible methods:

  • round(x) round.
  • ceil(x) rounds up the logarithm.
  • floor(x) rounds down X.
  • max(x,y,z,..., n) returns the highest value of x,y,z,..., n.
  • min(x,y,z,..., n) returns the lowest value of x,y,z,..., n.
  • abs(x) returns the absolute value of X
  • random() returns a random number between 0 and 1. (no parameters)
//round, ceil up, floor down
Math.round(1.2);//1
Math.round(1.6);//2
Math.ceil(1.2);//2
Math.ceil(1.5); //2
Math.ceil(-1.1); //-1
Math.floor(1.9); //1
Math.floor(1.1); //1
Math.floor(-1.1); //-2

random() generates a random string

Math.random().toString(36);//The default contains numbers and letters
Math.random().toString(36).replace(/[0-9]/g,'');//Clear number
//Formula of integer (n < m) of [n, m]
Math.floor(Math.random()*(m-n+1)+n);
//Returns an integer from 1 to 8, including 1 and 8
Math.floor(Math.random()*8+1);

Note: max and min in es3 can only accept two parameters, and multiple parameters can be accepted after es5

***

Topics: Javascript