Common built-in objects for JavaScript

Keywords: Javascript ECMAScript

JavaScript provides many common built-in objects, including Math object math, Date object date, Array object Array and String object String.

Math object

Use of Math objects

Math objects are used to perform math related operations on numbers. Instead of instantiating objects, you can directly use their static properties and methods. The common properties and methods of math objects are shown in the following table.

practice

Make the program randomly generate a number between 1 and 10, and let the user enter a number to judge the size of the two numbers. If the number entered by the user is greater than the random number, it will prompt "you guess big". If the number entered by the user is less than the random number, it will prompt "you guess small". If the two numbers are equal, it will prompt "Congratulations, you guessed right" to end the program.

function getRandom(min,max){
    return Math.floor(Math.random()*(max-min+1)+min);
  
}
var random = getRandom(1,10);
while(true){
    var p = prompt("Please enter the guessed number:");
    if(p>random){alert("Guess big")}
    else if(p<random){alert("Guess it's small")}
    else{alert("You guessed right");break;}
}

Date object

Use of date objects

The date object in JavaScript can only be used by instantiating the object with new Date(), which is the constructor of the date object. The date () constructor can pass in some parameters. The example code is as follows.

// Method 1: no parameters
var date1 = new Date();  
// Output: Wed Oct 16 2019 10:57:56 GMT+0800 (China standard time)
// Method 2: input year, month, day, hour, minute and second (the range of month is 0 ~ 11)
var date2 = new Date(2019, 10, 16, 10, 57, 56);
// Output: Sat Nov 16 2019 10:57:56 GMT+0800 (China standard time)
// Method 3: use string to represent date and time
var date3 = new Date('2019-10-16 10:57:56');
// Output: Wed Oct 16 2019 10:57:56 GMT+0800 (China standard time)

Common get methods for date objects

Common set methods for date objects

practice

Timestamp is the number of milliseconds elapsed from 0:0:0 on January 1, 1970 to the current UTC time.
Common ways to obtain time stamps are as follows:

// Method 1: through the valueof() or getTime() method of the date object
var date1 = new Date();
console.log(date1.valueOf()); // Example result: 1571119696188
console.log(date1.getTime()); // Example result: 1571119696188
// Method 2: use "+" operator to convert to numeric type
var date2 = +new Date();
console.log(date2);	// Example result: 15711196996190
// Method 3: use the Date.now() method added in HTML5
console.log(Date.now());	// Example result: 15711196996190

Array object

Array type detection

There are two common methods for array type detection: using the instanceof operator and using the Array.isArray() method.

var arr = [];
var obj = {};
// Mode 1
console.log(arr instanceof Array);	// Output result: true
console.log(obj instanceof Array);	// Output result: false
// Mode 2
console.log(Array.isArray(arr));	// Output result: true
console.log(Array.isArray(obj));	// Output result: false

Add or remove array elements

JavaScript array objects provide methods to add or delete elements. You can add new array elements at the end or beginning of the array, or remove array elements at the end or beginning of the array. The methods are as follows:

The push() and unshift() methods return the length of the new array, while the pop() and shift() methods return the removed array elements.

Array sorting

The JavaScript array object provides an array sorting method, which can sort array elements or reverse the order of array elements. The sorting method is as follows:

Note that the return value of the reverse() and sort() methods is the length of the new array.

Array index

In development, to find the position of the specified element in the Array, you can use the retrieval method provided by the Array object. The retrieval method is as follows:

By default, the retrieval starts from the position of the specified array index, and the retrieval method is the same as the operator "= =", that is, a successful result will be returned only when it is congruent.

practice

It is required to remove duplicate elements in a set of data.

function unique(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 = unique(['blue', 'green', 'blue']);
console.log(demo);	// Output result: (4) ["blue", "green"]

Convert array to string

During development, you can use the join() and toString() methods of array objects to convert arrays into strings. The methods are as follows:

practice

// Use toString()
var arr = ['a', 'b', 'c'];
console.log(arr.toString());	// Output results: a,b,c
// Use join()
console.log(arr.join());		// Output results: a,b,c
console.log(arr.join(''));		// Output result: abc
console.log(arr.join('-'));		// Output result: a-b-c

Array other methods

JavaScript also provides many other common array methods, such as filling array, connecting array, intercepting array elements, etc. the methods are as follows:

slice() and concat() methods return a new array after execution, which will not affect the original array. The remaining methods will affect the original array after execution.

String object

Use of string objects

The String object is created using new String(). The String is passed in the String constructor, which will save the String in the returned String object.

var str = new String('apple');	// Create string object
console.log(str);			// Output result: String {"apple"}
console.log(str.length);		// Get string length, output result: 5

Returns the position according to the character

String objects provide properties and methods for retrieving elements. The common properties and methods of string objects are as follows:

var str = 'HelloWorld';
str.indexOf('o');	    // Get the position where "o" first appears in the string, and return the result: 4
str.lastIndexOf('o');  // Get the last position of "o" in the string and return the result: 6

Returns characters based on position

The string object provides a method for obtaining a character in a string. The method is as follows:

String operation method

String object provides some properties and methods for intercepting string, connecting string and replacing string. The common properties and methods of string object are as follows:

practice

var str = 'HelloWorld';
str.concat('!');  // Splice characters at the end of the string, result: HelloWorld!
str.slice(1, 3);   // Intercept the content from position 1 to position 3, and the result is: el
str.substring(5);      // Intercept the content from position 5 to the end. Result: World
str.substring(5, 7);  // Intercept the content from position 5 to position 7. Result: Wo
str.substr(5);           // Intercept the content from position 5 to the end of the string. Result: World
str.substring(5, 7);  // Intercept the content from position 5 to position 7. Result: Wo
str.toLowerCase();  // Convert string to lowercase, result: helloworld
str.toUpperCase();  // Convert string to uppercase, result: HELLOWORLD
str.split('l');	  // Use "l" to cut the string, and the result: [he "," owor "," d "]
str.split('l', 3);	  // Limit cutting up to 3 times, result: ["he", "owor"]
str.replace('World', '!'); // Replace the string with the result: "Hello!"

More built-in objects can be queried on the Mozilla Developer Network (MDN).

Posted by Gargouil on Thu, 11 Nov 2021 12:24:00 -0800