Encapsulate your own mathematical objects, guess numbers, countdown effects, filter arrays, deduplicate arrays, return character positions, and count the most frequently occurring characters and times

Encapsulate your own mathematical objects, guess numbers, countdown effects, filter arrays, deduplicate arrays, return character positions, and count the most occurring characters and times

  • 1 Math object case
    • Encapsulate your own math object
    • guess the number game
    • Ask the user to guess a number between 1 and 50, but there are only 10 chances to guess
  • 2 Date object case
    • countdown effect
  • 3 Array object case
    • filter array
    • Array deduplication
  • 4 Examples of string objects
    • return character position
    • Count the most occurring characters and times
    • Comprehensive homework questions

1 Math object example

Encapsulate your own math object

//Use the object to encapsulate your own mathematical object, which contains the maximum and minimum values of PI
var myMath = {<!-- -->
PI: 3.141592653,
    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);
console.log(myMath.max(1,5,9));
console.log(myMath.min(1,5,9));

Guess the number game

The program randomly generates a number between 1 and 10, and asks the user to input a number.
1. If it is greater than the number, it will prompt: the number is too large, continue to guess.
2. If it is smaller than the number, it will prompt: the number is small, continue to guess.
3. If it is equal to the number, it will prompt: the guess is right, end the program.
// case analysis
// 1. Randomly generate an integer from 1 to 10, we need to use the Math.random() method
// 2. Need to guess until it is correct, so keep looping
// 3. The while loop is suitable and simpler
// 4. Core algorithm: use if else if multi-branch statement to judge greater than, less than, equal to

function getRandom(min, max) {<!-- -->
return Math. floor(Math. random() * (max - min + 1)) + min;
}
var random = getRandom(1,10);
while(true) {<!-- --> //infinite loop
var num = prompt('You guess?\
Enter a number between 1~10');
    if (num > random) {<!-- -->
    alert('The number is too big');
    } else if (num < random) {<!-- -->
        alert('The number is too small');
    } else {<!-- -->
        alert('Guess right!');
        break; // Exit the entire loop and end the program
    }
}




Ask the user to guess a number between 1 and 50, but there are only 10 chances to guess

function getRandom(min, max) {<!-- -->
return Math. floor(Math. random() * (max - min + 1)) + min;
}
var random = getRandom(1,50);
for (var i = 1; i <= 10; i ++ ) {<!-- -->
var num = prompt('You guess?\
Enter a number between 1~50');
if (num > random) {<!-- -->
alert('The number is too big');
    } else if (num < random) {<!-- -->
        alert('The number is too small');
    } else {<!-- -->
        alert('Guess right!');
        break; // Exit the entire loop and end the program
    }
    if (i == 10) {<!-- -->
        alert('Sorry, your number has run out');
    }
}

2 Date object case

Countdown effect

// case analysis
// 1. 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, such as 05 minutes minus 25 minutes, the result will be a negative number
// 2. Do it with a timestamp. Subtract the total number of milliseconds of the current time from the total number of milliseconds entered by the user, and the result is the number of milliseconds of the remaining time
// 3. Convert the total number of milliseconds of the remaining time into days, hours, minutes, and seconds (time stamps are converted into hours, minutes, and seconds)

function countDown(time) {<!-- -->
var nowTime = + new Date(); // returns the total milliseconds of the current time
    var inputTime = + new Date(time); // Returns the total number of milliseconds entered by the user
    var times = (inputTime - nowTime) / 1000; // what is returned is the total number of seconds of the remaining time divided by 1000 to convert milliseconds into seconds
    var d = parseInt(times / 60 / 60 / 24); // days
    d = d < 10 ? '0' + d : d;
    var h = parseInt(times / 60 / 60 % 24); // hours
    h = h < 10 ? '0' + h : h;
    var m = parseInt(times / 60 % 60); // minutes
    m = m < 10 ? '0' + m : m;
    var s = parseInt(times % 60); // seconds
    s = s < 10 ? '0' + s : s;
    return d + 'day' + h + 'hour' + m + 'minute' + s + 'second';
}
console.log(countDown('2022-12-1 20:00:00'));

3 array object case

Filter array

// There is an array [1500, 1200, 2000, 2100, 1800] containing salaries, and it is required to delete the salaries in the array that exceed 2000, and put the rest in 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[newArr. length] = arr[i];
        newArr. push(arr[i]);
}
}
console.log(newArr);

Array deduplication

// There is an array ['c','a','z','a','x','a','x','c','b'], and it is required to remove the array repeated elements
// case analysis:
// 1. Goal: Select the non-repeated elements in the old array and put them in the new array, keep only one of the repeated elements, and put them in the new array to remove the duplicates
// 2. Core algorithm: We traverse the old array, and then take the old array elements 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
// 3. How do we know if the element exists? Use the new array.indexOf (array element) If it returns -1, it means that there is no such element in the new array

// Encapsulate a deduplication function unique unique
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(['c','a','z','a','x','a','x','c','b']);
console. log(demo);

4 string object case

Return character position

// Find the position and number of occurrences of all o in the string "abcoefoxyozzopp"
// 1. Core algorithm: first find the position where the first o appears
// 2. Then as long as the result returned by indexOf is not -1, continue to search backward
// 3. Because indexOf can only find the first one, so the subsequent search uses the second parameter to add 1 to the current index to continue the search
var str = 'abcoefoxyzzop';
var index = str. indexOf('o');
var num = 0;
while (index !== -1) {<!-- -->
console. log(index);
num++;
index = str. indexOf('o', index + 1);
}
console.log('The number of occurrences of o is:' + num);

// homework
// ['red','blue','red','green','pink','red'], find the position and number of occurrences of red
var arr = ['red','blue','red','green','pink','red'];
var index = arr. indexOf('red');
var num = 0;
while (index !== -1) {<!-- -->
console. log(index);
num++;
index = arr. indexOf('red', index + 1);
}
console.log('The number of occurrences of red is:' + num);

Statistics of the most occurring characters and times

//Judge the most frequently occurring character in a string 'abcoefoxyozzopp', and count the number of times
// 1. Core algorithm: use charAt() to traverse the entire string
// 2. Store each character in the object, if the object does not have this attribute, it will be 1, if it exists, it will be + 1
// 3. Traverse the object to get the maximum value and the character
var str = 'abcoefoxyzzop';
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);
//Loop through objects
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 character that appears most is: ' + ch);

Comprehensive homework questions

//Given a string, such as: 'abaasdffggghhjjkkgfddsssss3444343', the question is as follows:
var str = 'abaasdffggghhjjkkgfddsssss3444343';
// 1. The length of the string
console.log('The length of the string is: ' + str.length);
// 2. Take out the character at the specified position, such as: 0, 3, 5, 9, etc.
console.log('The character whose index is 0 is: ' + str.charAt(0));
console.log('The character whose index is 3 is: ' + str.charAt(3));
console.log('The character whose index is 5 is: ' + str.charAt(5));
console.log('The character whose index is 9 is: ' + str.charAt(9));
// 3. Find whether the specified character exists in the above string, such as: i, c, b, etc.
if(str. indexOf('i') !== -1) {<!-- -->
console.log('i exists in the above characters!');
} else{<!-- -->
    console.log('i does not exist in the above characters!');
}
if(str. indexOf('c') !== -1) {<!-- -->
console.log('c exists in the above characters!');
} else{<!-- -->
    console.log('c does not exist in the above characters!');
}
if(str. indexOf('b') !== -1) {<!-- -->
    console.log('b exists in the above characters!');
} else{<!-- -->
    console.log('b does not exist in the above characters!');
}
// 4. Replace the specified characters, such as: replace g with 22, ss with b, etc.
console.log('g is replaced by 22, the string becomes:' + str.replace('g','22'));
console.log('ss is replaced by b, the string becomes:' + str.replace('ss','b'));
// 5. Intercept the string from the specified start position to the end position, such as: get the string of 1-5
console.log('The intercepted string of index number 1-5 is:' + str.slice(1,5));
// 6. Find the most frequently occurring character and the number of occurrences in the above string
var o = {<!-- -->}; // define an empty object
for (var i = 0; i < str. length; i ++ ) {<!-- -->
var chars = str.charAt(i); // chars is each character after traversal
    // If the character does not exist, the attribute value is 1; if it exists, the attribute value is increased by 1
    if (o[chars]) {<!-- -->
    o[chars] + + ;
    } else {<!-- -->
        o[chars] = 1;
    }
}
console.log(o); //output object o
// traverse the object
var max = 0; // define a maximum value, the initial value is 0
var ch = ''; // define an empty string
// start traversing
for (var k in o) {<!-- -->
if (o[k] > max) {<!-- -->
    max = o[k]; // assign the o[k] attribute value to max
        ch = k; // assign k attribute name to ch
    }
}
console. log(max);
console.log('The character with the most occurrences is: ' + ch);