JavaScript built-in objects

Keywords: Javascript Front-end


JavaScript provides many common built-in objects, including Math, Date, Array, String, and so on.

Familiarize yourself with built-in objects by querying documents

  1. Open the MDN website and find "Technology" - "JavaScript" in the navigation bar of the website. The effect is as follows.
  2. Scroll down the page and find Built-in Objects in the left sidebar. When you expand this item, you can see the directory links for all built-in objects, as shown in the following image.
  3. If you don't know the name of the object, you can also enter keywords in the search box on the page to search for it. With Math as an example, the effect diagram is shown below.
  4. When learning a method through documentation, there are basically four steps:
  • Functions of lookup methods
  • Viewing the meaning and type of a parameter
  • View the meaning and type of the return value
  • Testing with sample code

Math Object

Math objects are used to perform math-related operations on numbers. Instead of instantiating objects, they can be used directly with their static properties and methods. The common properties and methods of Math objects are listed below.

For example, generate a random number of a specified range

// Represents the generation of random values greater than or equal to min and less than max
Math.random() * (max - min) + min;
// Represents the generation of a random integer between 0 and any number
Math.floor(Math.random() * (max + 1));
// Represents the generation of a random integer between 1 and any number
Math.floor(Math.random() * (max + 1) + 1);

Example: Guess Numbers Game

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
var random = getRandom(1, 10);
while (true) {
  var num = prompt('Guess numbers, range 1~10 Between.');
  if (num > random) { alert('You guessed it'); } 
  else if (num < random) { alert('You guessed it was too small')} 
  else { alert('Congratulations, you guessed right'); break; }
}

Data Object

Date objects in JavaScript need to be instantiated using new Date(), which is the constructor of the date object. The Date() constructor can pass in some parameters, as shown in the sample code below.

  • Common get methods for date objects
  • Common set methods for date objects

    Examples include: Counting code execution times
  • A timestamp is the number of milliseconds that have elapsed since 0:0 a.m. on January 1, 1970 to the current UTC time.
  • Common ways to get timestamps are as follows:
// Mode 1: through the valueof() or getTime() method of the date object
var date1 = new Date();
console.log(date1.valueOf()); // Example result: 1571196996188
console.log(date1.getTime()); // Example result: 1571196996188
// Mode 2: Convert to a numeric type using the'+'operator
var date2 = +new Date();
console.log(date2);	// Example result: 1571196996190
// Mode 3: Use the new Dite.now() method of HTML5
console.log(Date.now());	// Example result: 1571196996190

For example: show that there are X days, X hours, X minutes and X seconds left until the end of the activity.

  • The core algorithm of countdown is to subtract the input time from the present time and get the remaining time which is the countdown time to display. This requires converting all the time into time stamps (milliseconds) to calculate, and the resulting milliseconds into days, hours, fractions, seconds.
function countDown(time) {
  var nowTime = +new Date();
  var inputTime = +new Date(time);
  var times = (inputTime - nowTime) / 1000;
  var d = parseInt(times / 60 / 60 / 24); d = d < 10 ? '0' + d : d;
  var h = parseInt(times / 60 / 60 % 24); h = h < 10 ? '0' + h : h;
  var m = parseInt(times / 60 % 60);m = m < 10 ? '0' + m : m;
  var s = parseInt(times % 60);  s = s < 10 ? '0' + s : s;
  return d + 'day' + h + 'time' + m + 'branch' + s + 'second';
}
// Example results: 05 days 23:06 minutes 10 seconds
console.log(countDown('2019-10-22 10:56:57')); 

Array object

Add or delete array elements

JavaScript array objects provide a way to add or delete elements by adding new array elements at the end or beginning of an array or moving them out at the end or beginning of an array. The methods are as follows:
==Note=:push() and unshift() methods return the length of the new array, while pop() and shift() methods return the removed array elements.
For example, filter arrays

  • Requires that data with wages up to 2000 or more be excluded from the array containing wages and that numbers less than 2000 be put back into the new array
var arr = [1500, 1200, 2000, 2100, 1800];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
  if (arr[i] < 2000) {
    newArr.push(arr[i]); // Equivalent to: newArr[newArr.length] = arr[i];
  }
}
console.log(newArr);  // Output results: (3) [1500, 1200, 1800]

Array sorting

JavaScript array objects provide a way to sort arrays, which can sort array elements or reverse the order of array elements. The sorting method is as follows:

==Note==:

  1. The return values of the reverse() and sort() methods are the length of the new array.
  2. sort(): Sort by character encoding order by default; To sort in another order, you need to customize the function
function numberOrder(a,b){
	return a-b
}

Array Index

In development, to find the location of a specified element in an array, you can use the retrieval method provided by the Array object. The retrieval methods are as follows:

For example, array removes duplicate elements

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: (4) ['blue','green']

Array to String


For example:

// Use toString()
var arr = ['a', 'b', 'c'];
console.log(arr.toString());	// Output results: a,b,c
// Using 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

Other methods

JavaScript also provides many other common array methods. For example, fill arrays, join arrays, intercept array elements, and so on. The methods are as follows:

The slice() and concat() methods return a new array after execution without affecting the original array. The remaining methods will affect the original array after execution.

String Object

Return position based on character

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

var str = 'HelloWorld';
str.indexOf('o');	    // Gets the position of the first occurrence of "o" in a string and returns the following result:4
str.lastIndexOf('o');  // Gets the position of the last occurrence of "o" in the string and returns the following result:6

For example, you need to find the location and number of occurrences of all specified elements in a set of strings. The string is'Hello World, Hello JavaScript'.

var str = 'Hello World, Hello JavaScript';
var index = str.indexOf('o');
var num = 0;
while (index != -1) {
  console.log(index);		  // Output in sequence: 4, 7, 17
  index = str.indexOf('o', index + 1);
  num++;
}
console.log('o The number of occurrences is:' + num);  // o Number of occurrences is:3

Return characters based on position

String objects provide a way to get a character in a string. The methods are as follows:

var str = 'HelloWorld';
var str = 'Apple';
console.log(str.charAt(3));	          // Output result: 1
console.log(str.charCodeAt(0));   // Output result: 65 (ASCII code of character A is 65)
console.log(str[0]);	          // Output result: A

For example, use the charAt() method to program to count the most characters and times in a string.

var str = 'Apple';
// Step 1, Count the occurrences of each character
var o = {};
for (var i = 0; i < str.length; i++) {
  var chars = str.charAt(i);	// Save every character in the string with chars
  if (o[chars]) {	               // Use the properties of the object to easily find elements
    o[chars]++;
  } else {  o[chars] = 1; }
}
console.log(o);		// Output: {A: 1, p: 2, l: 1, e: 1}
// Step 2, Count the characters that appear most
var max = 0;		// Save maximum occurrences
var ch = '';		// Save the characters that occur most often
for (var k in o) {
  if (o[k] > max) {
    max = o[k];
    ch = k;
  }
}
// Output: "The character that appears most is: p, which occurs twice in total"
console.log('The characters that appear most are:' + ch + ',Come together' + max + 'second');

String manipulation method

String objects provide properties and methods for intercepting strings, connecting strings, and replacing strings. Common properties and methods of string objects are as follows:

var str = 'HelloWorld';
str.concat('!');  // Stitch the 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 from position 5 to the end, result: World
str.substring(5, 7);  // Intercept content from position 5 to position 7, result: Wo
str.substr(5);           // Intercepts from position 5 to the end of the string, resulting in: World
str.substring(5, 7);  // Intercept 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 is: ["He", "", "oWor", "d"]
str.split('l', 3);	  // Limit cutting up to three times, result: ['He',','oWor']
str.replace('World', '!'); // Replace string, result:'Hello!'

For example: User names are in the range of 3-10 in length and cannot appear in any case of the sensitive word admin.

var name = prompt('enter one user name');
if (name.length < 3 || name.length > 10) {
  alert('User name length must be 3~10 Between.');
} else if (name.toLowerCase().indexOf('admin') !== -1) {
  alert('User names cannot contain sensitive words: admin. ');
} else {
  alert('Congratulations, this username can be used');
}

Posted by meow on Fri, 03 Dec 2021 10:41:40 -0800