14. JavaScript built-in object
The following questions need to be considered:
- What are built-in objects?
- How to specify API usage based on document query?
- How do I use common methods for Math objects?
- How to use common methods of Date object?
- How to use common methods of Array objects?
- How to use common methods of String objects?
1. Built in object
- There are three kinds of objects in JavaScript: custom object, built-in object and browser object;
- The first two objects are the basic content of JS and belong to ECMAScript; The third browser object is unique to JS, and we explain the JS API;
- Built in objects refer to some of the built-in objects of JS language. These objects are used by developers and provide some commonly used or most basic and necessary functions (properties and methods).
- The biggest advantage of built-in objects is to help us develop quickly.
- JavaScript provides several built-in objects: Math, Date, Array, string, etc
2. Check documents
2.1 - MDN
To learn how to use a built-in object, just learn how to use its common members. We can learn by looking up documents, MDN and W3C.
Mozilla Developer Network (MDN) provides information about Open Web technology (Open Web), including HTML, CSS and API s for World Wide Web and HTML5 applications.
2.2 - how to learn methods in objects
- Review the function of this method
- Check the meaning and type of parameters inside
- View the meaning and type of the return value
- Test through demo
3. Math object
3.1 - Math overview
Math object is not a constructor, so we don't need new to call it, but just use the properties and methods inside.
Math.PI is the ratio of the circumference of a circle to its diameter (PI)
console.log(Math.PI); //3.141592653589793
- Math.PI is a static attribute of math.
Math. The max() function returns the maximum value in a set of numbers.
console.log(Math.max(1, 3, 9)); //9 console.log(Math.max(1, 3, 'Red bean paste')); //NaN console.log(Math.max()); //-Infinity
- NaN is returned if at least one of the given parameters cannot be converted to a number
- If there are no parameters, the result is - Infinity.
- Math.max is math's static method.
Math.min() returns the minimum of zero or more values.
console.log(Math.min(1, 3, 9)); //1 console.log(Math.min(1, 3, 'Red bean paste')); //NaN console.log(Math.min()); //Infinity
- NaN is returned if at least one of the given parameters cannot be converted to a number
- If there are no parameters, the result is Infinity.
- Math.min is math's static method.
Case: encapsulating your own mathematical object
Using objects to encapsulate their own mathematical objects; There are maximum and minimum PI values;
var myMath = { PI: 3.1415926, max: function() { var max = arguments[0] for (var i = 1; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; }, min: function() { var min = arguments[0] for (var i = 1; i < arguments.length; i++) { if (arguments[i] < min) { min = arguments[i]; } } return min; } } console.log(myMath.PI); //3.1415926 console.log(myMath.max(1, 3, 9)); //9 console.log(myMath.min(1, 3, 9)); //1
Math. The abs() function returns the absolute value of the specified number "x".
console.log(Math.abs(1)); //1 console.log(Math.abs('-1')); //1 console.log(Math.abs('Red bean paste')); //NaN console.log(Math.abs()); //NaN console.log(Math.abs(null)); //0
- Math.abs() is a static method in math
- If you pass in a non numeric string or undefined/empty variable, NaN will be returned. Passing in null will return 0.
3.2 - three rounding methods
Math.floor() returns the largest integer less than or equal to a given number.
console.log(Math.floor(1.1)); //1 console.log(Math.floor(1.9)); //1 console.log(Math.floor(-1.9)); //-2 console.log(Math.floor(-1.1)); //-2
- Understandable, math Floor() is rounded down
- A number that represents the largest integer less than or equal to the specified number.
Math. The ceil() function returns the smallest integer greater than or equal to a given number.
console.log(Math.ceil(1.1)); //2 console.log(Math.ceil(1.9)); //2 console.log(Math.ceil(-1.9)); //-1 console.log(Math.ceil(-1.1)); //-1
- Understandable, math Ceil() is rounded up
- The smallest integer greater than or equal to a given number.
**Math. The round() * * function returns a number to the nearest integer after rounding.
console.log(Math.round(1.1)); //1 console.log(Math.round(1.5)); //2 console.log(Math.round(-1.5)); //-1 console.log(Math.round(-1.6)); //-2 console.log(Math.round(-1.1)); //-1
- If the fractional part of the parameter is exactly equal to 0.5, it is rounded to the adjacent integer in the positive infinite (+ ∞) direction.
- The value of a given number is rounded to the nearest integer.
3.2 - random number method (random)
Math. The random() function returns a floating-point number with a pseudo-random number in the range of 0 (inclusive) and 1 (exclusive).
console.log(Math.random());
- This method is not followed by parameters;
Get a random integer between two numbers, including two numbers:
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(getRandom(1, 10));
Random roll call
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } var arr = ['Red bean paste', 'pineapple', 'tomato', 'potato', 'Tomatoes', 'Pineapple', 'salad', 'Spinach', 'eggplant', 'Carrot', 'Coconut', 'Red bean']; console.log(arr[getRandom(0, arr.length - 1)]);
Case: number guessing game
The program randomly generates a number between 1 and 10, and allows the user to enter a number,
-
If it is greater than the number, it will prompt that the number is large and continue to guess;
-
If it is less than this number, it will prompt that the number is small and continue to guess;
-
If it is equal to this number, you will be prompted to guess correctly and end the program.
Case study:
- To randomly generate an integer of 1 ~ 10, we need to use math Random() method.
- You need to guess until you get it right, so keep cycling.
- It's easier to use a while loop.
- Core algorithm: use if else if multi branch statements to judge greater than, less than and equal to.
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } var randNum = getRandom(1, 10); while (true) { //Build an endless loop var num = prompt("Guess, this number is 1~10 Which integer between?"); if (num > randNum) { alert("Guess it's too big"); } else if (num < randNum) { alert("Guess it's small") } else { alert("congratulations! You guessed right"); break; //Exit the entire cycle } }
Requirement: the user guesses a number between 1 and 50, but has only 10 chances to guess
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } var randNum = getRandom(1, 50); var i = 1; var num = prompt("Guess, this number is 1~50 Which integer between?"); while (true) { //Build an endless loop if (num > randNum) { alert("Guess it's too big"); var num = prompt("You still have" + (10 - i) + "Second chance"); } else if (num < randNum) { alert("Guess it's small"); var num = prompt("You still have" + (10 - i) + "Second chance"); } else { alert("congratulations! You guessed right"); break; //Exit the entire cycle }; i++; if (i == 10) { break; } }
4. Date object
4.1 - Date overview
The Date object is different from the Math object. It is a constructor, so we need to instantiate it before we can use it.
The Date instance is used to process Date and time.
4.2 - use of date() method
- Get current time must be instantiated
var now = new Date(); console.log(now); //Sun Jul 18 2021 15:58:21 GMT+0800 (China standard time)
- Date() is a constructor and must be called with new to create our date object;
- If no parameters are provided, the newly created Date object represents the Date and time of the instantiation time (returning the current time of the current system).
- Parameters of the Date() constructor
If there is time in parentheses, the time in the parameter is returned. For example, the date format string is' 2019-5-1 ', which can be written as new Date('2019-5-1') or new Date('2019/5/1 ').
var data1 = new Date(2021, 02, 02); console.log(data1); //Tue Mar 02 2021 00:00:00 GMT+0800 (China standard time) /*March is returned, not February*/ var data2 = new Date('2021-2-1 8: 8: 8') console.log(data2); //Mon Feb 01 2021 08:08:08 GMT+0800 (China standard time) var data3 = new Date('2021/2/1') console.log(data3); //Mon Feb 01 2021 00:00:00 GMT+0800 (China standard time)
4.3 - date formatting
- We want a date in the format of 2019-8-8:8:8. What should we do?
- We need to get the part specified by the date, so we need to get this format manually.
Method name | explain | code |
---|---|---|
getFullYear() | Get current year | date.getFullYear() |
getMonth() | Get current month (0-11) | date.getMonth() |
getDate() | Get the date of the day | date.getDate() |
getDay() | Get day of the week (Sunday 0 to Saturday 6) | date.getDay() |
getHours() | Get current hour | date.getHours() |
getMinutes() | Gets the current minute | date.getMinutes() |
getSeconds() | Gets the current seconds | date.getSeconds() |
Get date
var date = new Date(); console.log(date.getFullYear()); //Returns the year of the current date console.log(date.getMonth() + 1); //The month returned in the month is 1 month smaller, so it should be + 1 console.log(date.getDate()); // What number is returned; console.log(date.getDay()); // Return on Monday is 1; The return on Saturday is 6; But Sunday returns 0;
Write a Friday, October 1, 2021
var date = new Date(); var year = date.getFullYear(), month = date.getMonth() + 1, dates = date.getDate(), day = date.getDay(); var arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; console.log('Today is' + year + 'year' + month + 'month' + dates + 'day' + arr[day]);//Today is Friday, October 1, 2021
Get hours, minutes and seconds
var date = new Date(); console.log(date.getHours()); console.log(date.getMinutes()); console.log(date.getSeconds());
It is required to encapsulate a function to return the current hour, minute and second
function getTime() { var date = new Date(); var h = date.getHours(), m = date.getMinutes(), s = date.getSeconds(); h = h < 10 ? '0' + h : h; m = m < 10 ? '0' + m : m; s = s < 10 ? '0' + s : s; return h + ':' + m + ':' + s; } console.log(getTime());
4.4 – get the total milliseconds of the date
The Date object is based on the number of milliseconds from January 1, 1970 (world standard time);
- Obtain the total number of milliseconds (timestamp) of Date; It is not the number of milliseconds of the current time, but the number of milliseconds since January 1, 1970.
- Get through valueOf()/getTime():
var date = new Date(); console.log(date.valueOf()); //The total number of microseconds from 1970.1.1 console.log(date.getTime());
- Simple writing (most commonly used):
var date = +new Date(); console.log(date);
- H5 new method:
console.log(Date.now());
Case: countdown effect
Make a countdown effect;
case analysis
- Core algorithm: the input time minus the current time is the remaining time, that is, the countdown, but you can't subtract the hours, minutes and seconds. For example, if you subtract 25 minutes from 05 minutes, the result will be negative.
- Do it with a timestamp. The total number of milliseconds of the user input time minus the total number of milliseconds of the current time is the number of milliseconds of the remaining time.
- Convert the total number of microseconds of the remaining time into days, hours, minutes and seconds (the timestamp is converted to minutes and seconds)
function countDown(time) { var nowTime = +new Date(), inputTime = +new Date(time), times = (inputTime - nowTime) / 1000, d = parseInt(times / 60 / 60 / 24), //Calculation days h = parseInt(times / 60 / 60 % 24), //Calculate hours m = parseInt(times / 60 % 60), //Calculate minutes s = parseInt(times % 60); //Calculate seconds d = d < 10 ? '0' + d : d; h = h < 10 ? '0' + h : h; m = m < 10 ? '0' + m : m; s = s < 10 ? '0' + s : s; return d + 'day' + h + 'Time' + m + 'branch' + s + 'second' } console.log(countDown('2021/10/1'));//74 days 06:11:34
5. Array object
5.1 - two ways to create arrays:
- Using array literals
var arr = [2, 3] console.log(arr); //[2, 3]
- Using new Array()
var arr = new Array(); //An empty array was created var arr1 = new Array(2); //An empty array with an array length of 2 was created var arr2 = new Array(2, 3); // Equivalent to [2,3] console.log(arr); //[] console.log(arr1); //[empty × 2] console.log(arr2); //[2, 3]
5.2 - detect whether it is an array
- instanceof operator; It can be used to detect whether it is an array:
var arr = []; var obj = {}; console.log(arr instanceof Array); //true console.log(obj instanceof Array); //false
- Array.isArray() is used to determine whether the value passed is an array.
var arr = []; var obj = {}; console.log(Array.isArray(arr)); //true console.log(Array.isArray(obj)); //false
- H5 new method; Supported by IE9 and above
5.3 - Methods for adding and deleting array elements
- push() adds one or more array elements to the end of our array:
var arr = [1, 2, 3] arr.push(4); console.log(arr.push('Red bean paste')); //5 console.log(arr); //[1, 2, 3, 4, "bean paste"]
- push() can add new elements to the array;
- The push() parameter can be written directly to the array element;
- After push(), the returned result is the length of the new array.
- The original array will also change.
- unshift() adds one or more array elements at the beginning of our array:
var arr = [1, 2, 3] arr.unshift(4); console.log(arr.unshift('Red bean paste')); //5 console.log(arr); //["bean paste", 4, 1, 2, 3]
- unshift() can append new elements to the array;
- The unshift() parameter can be written directly to the array element;
- After unshift(), the result returned is the length of the new array.
- The original array will also change.
- pop() which deletes the last element of the array:
var arr = [0, 1, 2, 3, 'Red bean paste', 'tomato', 'pineapple'] arr.pop(); console.log(arr.pop()); //tomato console.log(arr); //[0, 1, 2, 3, "bean paste"]
- pop() can delete the last element of the array, only one at a time;
- pop() has no parameters;
- After pop() is completed, the returned result is the deleted element.
- The original array will also change.
- shift() which deletes the first element of the array:
var arr = [0, 1, 2, 3, 'Red bean paste', 'tomato', 'pineapple'] arr.shift(); console.log(arr.shift()); //1 console.log(arr); // [2, 3, "bean paste", "tomato", "pineapple"]
- shift() can delete the last element of the array, only one at a time;
- shift() has no parameters;
- After shift(), the result returned is the deleted element.
- The original array will also change.
Summary:
Method name | explain | Return value |
---|---|---|
Push (parameter...) | Adding one or more array elements at the end of the array modifies the original array. | Length of new array |
Unshift (parameter...) | Adding one or more array elements at the beginning of the array modifies the original array. | Length of new array |
pop() | Delete the last element of the array and modify the original array. | Deleted element |
shift() | Delete the last element of the array and modify the original array. | Deleted element |
Cases: filtering arrays
There is an array containing wages [1500, 1200, 2000, 2100, 1800]. It is required to delete the wages exceeding 2000 in the array and put the rest 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]); } } console.log(newArr); //[1500, 1200, 1800]
5.4 - array sorting
- reverse() flips the array
var arr = ['Red bean paste', 'pineapple', 'tomato', 'potato', 'Tomatoes']; arr.reverse(); console.log(arr); //["tomato", "potato", "tomato", "pineapple", "bean paste"]
- sort() array sort
var arr = [2, 5, 8, 6, 11, 23, 45]; arr.sort(function(a, b) { return a - b;//Ascending order }); console.log(arr); //[2, 5, 6, 8, 11, 23, 45] arr.sort(function(a, b) { return b - a;//Descending order }); console.log(arr); //[45, 23, 11, 8, 6, 5, 2]
Summary
Method name | explain | Return value |
---|---|---|
reverse() | Invert the order of elements in the array without parameters | This method will change the original array and return a new array |
sort() | Sort the elements of the array | This method will change the original array and return a new array |
5.5 - array index method
Method to return the index number of an array element:
- indexOf() (array element) is used to return the index number of the array element; Find from the front.
var arr = ['Red bean paste', 'pineapple', 'tomato', 'Red bean paste', 'Tomatoes']; console.log(arr.indexOf('Red bean paste')); //0 console.log(arr.indexOf('blue')); //-1
- lastIndexOf returns the index number of the array element; Start at the back.
var arr = ['Red bean paste', 'pineapple', 'tomato', 'Red bean paste', 'Tomatoes']; console.log(arr.lastIndexOf('Red bean paste')); //3 console.log(arr.lastIndexOf('blue')); //-1
Summary
Method name | explain | Return value |
---|---|---|
indexOf() | Finds the first index of a given element in an array | Returns the index number if it exists, - 1 if it does not exist. |
lastIndexOf() | The index of the last in the array, | Returns the index number if it exists, - 1 if it does not exist. |
Case: array de duplication (key case)
There is an array ['c ',' a ',' Z ',' a ',' x ',' a ',' x ',' C ',' B '], which requires the removal of duplicate elements in the array.
Case study:
Objective: select the non duplicate elements in the old array and put them into the new array. Only one duplicate element is retained and put them into the new array for duplication.
Core algorithm: we traverse the old array, and then take the old array element to query the new array. If the element has not appeared in the new array, we will add it, otherwise we will not add it.
How do we know that the element does not exist? Use the new array Indexof (array element) - 1 if returned; This means that there is no such element in the new array.
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 arr1 = ['c', 'a', 'z', 'a', 'x', 'a', 'x', 'c', 'b'] console.log(unique(arr1)); //["c", "a", "z", "x", "b"]
5.6 - Convert array to string
- toString() converts our array into a string;
var arr = [1, 2, 3] console.log(arr.toString()); //1,2,3
- Join (separator)
var arr = ['Red bean paste', 'tomato', 'Tomatoes'] console.log(arr.join()); //Bean paste, tomato, tomato console.log(arr.join('/')); //Bean paste / tomato / Tomato console.log(arr.join('&')); //Bean paste & tomato & Tomato
Summary
Method name | explain | Return value |
---|---|---|
toString() | Convert the array into a string, separating each item with a comma | Returns a string |
join('separator ') | Method is used to convert all elements in an array into a string. | Returns a string |
5.7 - inquiry after class
Method name | explain | Return value |
---|---|---|
concat() | Connecting two or more arrays does not affect the original array | Returns a new array |
slice() | Array interception slice(begin, end) | Returns a new array of intercepted items |
splice() | Delete splice from the array (the number to be deleted starts from the first few) | Returns a new array of deleted items. Note that this will affect the original array |
- slice() and slice() have basically the same purpose. It is suggested that students focus on slice()
- The concat (value) method is used to combine two or more arrays. This method does not change the existing array, but returns a new array.
- value
-
- Arrays and / or values will be merged into a new array.
var arr = [1, 2, 3]; var arr2 = ['one', 'two', 'three']; console.log(arr.concat(arr2, 'Red bean paste')); //[1, 2, 3, "one", "two", "three", "bean paste"] console.log(arr); //[1, 2, 3]
- Method does not change an existing array
- Returns a new array
- slice(begin,end) method returns a new array object
- begin (optional)
-
- Extract the index at the beginning (starting from 0), and extract the original array elements from this index.
- If the parameter is negative, it means to extract from the penultimate element in the original array.
- If begin is omitted, slice starts with index 0.
- If begin exceeds the index range of the original array, an empty array is returned.
- end (optional)
-
- The index at the end of the extraction (starting from 0) at which the extraction of the original array elements ends.
- slice will extract all elements in the original array whose indexes are from begin to end (including begin but not end).
- If end is omitted or end is greater than the length of the array; slice will be extracted to the end of the original array.
var arr = [1, 2, 3, 'one', 'two', 'three', 'Red bean paste']; console.log(arr.slice()); //[1, 2, 3, "one", "two", "three", "bean paste"] console.log(arr.slice(3)); //["one", "two", "three", "bean paste"] console.log(arr.slice(3, 6)); //["one", "two", "three"] console.log(arr); //[1, 2, 3, "one", "two", "three", "bean paste"]
- **splice(start,count,items...)** Modify the array by deleting or replacing existing elements or adding new elements in place
-
start (optional)
-
- Specifies the start position of the modification (counted from 0). If the length of the array is exceeded, add content from the end of the array;
- If it is negative, it indicates the number of bits from the last bit of the array (counting from - 1, which means - n is the nth element from the bottom and equivalent to array.length-n);
- If the absolute value of a negative number is greater than the length of the array, the start position is bit 0.
-
count (optional)
-
- Integer representing the number of array elements to be removed.
-
items (optional)
-
- The elements to be added to the array start at the start position.
- If not specified, splice() will delete only the array elements.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] console.log(arr.splice()); //[] /*Delete add element from index 1*/ console.log(arr.splice(1, 2, 'Red bean paste', 'potato'));//[2, 3] console.log(arr);//[1, "bean paste", "potato", 4, 5, 6, 7, 8, 9, 10]
- This method changes the original array.
- If the element is not deleted, an empty array is returned.
- An array of deleted elements as the return value.
6. String object
6.1 - basic package type
To facilitate the manipulation of basic data types, JavaScript also provides three special reference types: String, Number, and Boolean.
The basic wrapper type is to wrap a simple data type into a complex data type, so that the basic data type has properties and methods.
//What's wrong with the following code? var str = 'dousha'; console.log(str.length); //6
In principle, basic data types have no properties and methods, while objects have properties and methods, but the above code can be executed because JavaScript will package basic data types as complex data types. The execution process is as follows:
/*1.Generate temporary variables and wrap simple types into complex data types*/ var temp = new String('dousha'); /* 2.Assign to the character variable we declare*/ str = temp; /*3.Destroy temporary variables*/ temp = null;
6.2 - immutability of strings
It means that the value inside is immutable. Although it seems that the content can be changed, in fact, the address has changed and a new memory space has been opened up in the memory.
Because our strings are immutable, don't splice a large number of strings;
var str = 'red'; str = 'blue';
6.3 - return position according to character
All methods of string will not modify the string itself (the string is immutable), and a new string will be returned after the operation is completed.
Method name | explain |
---|---|
indexOf('character to find ', [' starting position ']) | Returns the position of the specified content in the meta string. If it is not found, it returns - 1. The starting position is the index index number |
lastIndexOf() | Look back and forward, only the first one that matches |
- str.indexOf('character to find ', [starting position])
var str = 'Fried tomato with tomato,Fried pineapple with pineapple'; console.log(str.indexOf('fry')); //2 console.log(str.indexOf('fry', 3)); //9
Case: return character position
Find the location and number of occurrences of all o in the string "abcoefoxyozopp".
Idea:
- Core algorithm: first find the location where the first o appears;
- Then, as long as the result returned by indexOf is not - 1, continue to look back;
- Because indexOf can only find the first one, the subsequent search uses the second parameter to add 1 to the current index to continue the search.
var str = "abcoefoxyozopp"; var index = str.indexOf('o'); var j = 0; while (index !== -1) { console.log(index); j++; index = str.indexOf('o', index + 1) } console.log('o The number of occurrences is:' + j + 'second');
Homework after class: ['Red', 'blue', 'Red', 'green', 'pink', 'Red'], find the location and frequency of red
var arr = ['red', 'blue', 'red', 'green', 'pink', 'red']; var index = arr.indexOf('red'); var j = 0; while (index !== -1) { console.log(index); j++; index = arr.indexOf('red', index + 1) } console.log('red The number of occurrences is:' + j + 'second');
6.4 - return characters according to position (emphasis)
- charAt(index) returns the character at the specified position
var str = 'dousha'; console.log(str.charAt(2)); //u //Traversal character for (var i = 0; i < str.length; i++) { console.log(str.charAt(i)); }
- charCodeAt(index) gets the ASCII code of the character at the specified position
var str = 'dousha'; console.log(str.charCodeAt(2)); //117
- Used to judge which key the user pressed;
- str[index] gets the character at the specified position
var str = 'dousha'; console.log(str[0]); //d
Summary:
Method name | explain | use |
---|---|---|
charAt(index) | Returns the character at the specified position (the index number of the index string) | str.charAt(index) |
charCodeAt(index) | Gets the ASCII code (index index number) of the character at the specified position | str.charCodeAt(index) |
str[index] | Gets the character at the specified position | HTML5, IE8 + support and charAt() equivalent| |
To determine whether the attribute object ['key']
var o = { age: 18, } if (o['sex']) { console.log('There is the object in it'); } else { console.log('The object does not exist');//The object does not exist }
Judge the character that appears the most times in a string 'abcoefoxyozopp', and count its times.
- Core algorithm: use charAt() to traverse this string
- Store each character to the object. If the object does not have this attribute, it will be 1. If it exists, it will be + 1;
- Traverse the object to get the maximum value and the character.
var str = 'abcoefoxyozzopp'; var o = {}; for (var i = 0; i < str.length; i++) { var char = str.charAt(i); if (o[char]) { o[char]++; } else { o[char] = 1; } } var max = 0; var count = 0; for (var k in o) { if (o[k] > max) { max = o[k]; count = k; } } console.log('The most frequent characters are:' + count, 'Number of occurrences:' + max);//The characters with the most occurrences are: o Occurrences: 4
6.5 - string operation method (key)
Method name | explain |
---|---|
concat(str1,str2,str3..) | The concat() method is used to connect two or more strings. Splice string, equivalent to +, + is more commonly used |
substr(start,length) | Start at the start position (index number) and take the number of length. Remember this |
slice(start, end) | Start from the start position and intercept to the end position, but end cannot (both of them are index numbers) |
substring(start, end) | Start from the start position and intercept to the end position. The end can't get basically the same as slice, but it doesn't accept negative values |
- concat(str1,str2,str3..)
var str = 'hello'; console.log(str.concat("world")); //helloworld console.log(str); //hello
- Do not change the original string;
- Returns a new string.
- substr(start,length)
- start the starting position of interception;
- length intercepts several characters.
var str = 'hello'; console.log(str.substr(3, 2)); //lo console.log(str); //hello
- Returns the intercepted character;
- Do not change the original string.
- replace(value1,value2) replaces characters, and only the first character will be replaced;
- value1: replaced character;
- value2: character after replacement.
var str = 'hello'; console.log(str.replace('l', 'w')); //hewlo console.log(str); //hello /*Replace all l characters*/ var str1 = str.replace('l', 'w'); while (str1.indexOf('l') !== -1) { str1 = str1.replace('l', 'w'); } console.log(str1); //hewwo
- Do not change the original string.
- Returns a new string.
- Convert split('separator ') character to array (join('separator') converts array to string)
var str2 = 'red,pink,blue' console.log(str2.split(',')); // ["red", "pink", "blue"] console.log(str2); //red,pink,blue
6.8 - after class review
toUpperCase() – convert to uppercase
- The toUpperCase() method converts the string calling the method to uppercase and returns it (if the value calling the method is not of string type, it will be cast)
var str = 'i can fiy' console.log(str.toUpperCase()); //I CAN FIY console.log(str); //i can fiy
toLowerCase() – convert to lowercase
- toLowerCase() converts the string value calling the method to lowercase and returns the value.
var str = 'I LIKE CANDY' console.log(str.toLowerCase()); //i like candy console.log(str); //I LIKE CANDY
Job:
Given a string, such as "abaasdffggghhjjkkgfddsssss3444343", the problem is as follows:
- The length of the string;
- Take out the characters in the specified position, such as 0, 3, 5, 9, etc;
- Find out whether the specified character exists in the above string, such as i, c, b, etc;
- Replace the specified characters, such as g with 22, ss with b and other operation methods;
- Intercept the string from the specified start position to the end position, such as: obtain the string of 1-5;
- Find out the character with the most occurrences and the number of occurrences in the above string.
var str = 'abaasdffggghhjjkkgfddsssss3444343'; /* 1.Length of output string */ console.log(str.length); /* 2.Returns the character at the specified position */ console.log(str.charAt(0)); console.log(str.charAt(3)); console.log(str.charAt(5)); console.log(str.charAt(9)); /*3.Encapsulate the process of finding characters into functions*/ function checkUp(a) { var result = ''; for (var i = 0; i < str.length; i++) { var char = str.charAt(i); if (char == a) { result = "This element exists in the string."; break; } else { result = "This element does not exist in the string."; } } return result; } /*Call function*/ console.log(checkUp('i')); console.log(checkUp('c')); console.log(checkUp('b')); /*4.Encapsulate the process of replacing characters into functions*/ function newStr(a, b) { var newStr = str.replace(a, b) while (newStr.indexOf(a) !== -1) { newStr = newStr.replace(a, b) } return newStr; } /*Bring in the actual parameter output result*/ console.log(newStr('g', '22')); console.log(newStr('ss', 'b')); /*5.Intercept string*/ console.log(str.substr(5, 5)); /*6.Find the character with the most occurrences and the number of occurrences*/ var obj1 = {}; var max = 0; var count = 0; for (var i = 0; i < str.length; i++) { var char = str.charAt(i); if (obj1[char] > 0) { obj1[char]++; } else { obj1[char] = 1; } } for (var k in obj1) { if (obj1[k] > max) { max = obj1[k]; count = k; } } console.log('The most frequent characters are:' + count + ' ,Number of occurrences:' + max);