js practice questions
- Get all even numbers between 1 and 100
<script>
for(var i = 1;i <= 100;i++){
if(i % 2 == 0){
console.log(i);
}
}
for(var a = 2;a <= 100;a+=2){
console.log(a);
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- Calculate the product of 1-100
<script>
var num = 1;
for(var n = 1; n<= 10;n++){
num *= n;
// (num,n);
}
console.log(num);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- The large horse carries 2 stones of grain, the medium horse carries 1 stone of grain, and the two small horses carry one stone of grain. 100 horses are to be used to carry 100 stones of grain, how should they be deployed?
<script>
var n = 0;
for(var x = 0;x <= 100;x++){
for(var y = 0;y <= 100;y++){
for(var z = 0;z <= 100;z++){
if(x + y + z == 100 && x * 2 + y + z / 2 == 100){
// (`Large horse ${x}; medium horse ${y}; small horse ${z}`).
n++;
}
}
}
}
console.log(n);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- There was a monkey in the park with a bunch of peaches. Every day the monkey ate half of the total number of peaches and threw away one bad one out of the remaining half. On the seventh day, the monkey opens his eyes and realizes that there is only one peach left. How many peaches were there in the park at the beginning?
<script>
var a = 1;
for(var i = 1;i < 7;i++){
a = (a + 1) * 2;
}
console.log(a);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- Sum of numbers between 1 and 100 that are not divisible by 3
<script>
// Declare a variable that stores the sum of all the numbers that satisfy the condition.
var sum = 0;
// 1~100 Loops Numbers not divisible by 3 Judgment Conditions Sums Operators
// Find all the numbers between 1 and 100
for(var i = 1; i <= 100; i++){
// Determine the number that is not divisible by 3. modulo % i modulo 3 is 0.
if(i % 3 != 0){
// Accumulate +=
sum += i; // When i is 1, sum = 0+1; when i is 2, sum = 1+2,...
}
}
alert('The sum of the numbers between 1 and 100 that are not divisible by 3 is ' + sum);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- Enter the number of times the class motto "Happy Learning, Serious Life!" is displayed according to the number of times you enter it. What should I write?
<script>
// Enter the number of times prompt() needs to store the value you entered Loop
// Enter the number of displays
var num = prompt('Please enter the number of displays:') * 1;
// Loop range 0-num
for(var i = 0; i < num; i ++){
document.write(' Class motto: Happy learning, serious life! <br />');
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
-
Loop EntryJavascriptStudent grades in classes, percentage of students with scores greater than or equal to 80
analyze
- Go through the cycle and get a score greater than or equal to80Number of students scoringnum
- Judgement: if grade **<80**, not implementednum++The next cycle goes straight to the next one.
<script>
// Loop prompt Greater than or equal to 80 points Condition Percentage of Students
// Total number of persons fulfilling the conditions and total class size
// Enter the total class size
var sumNum = prompt('Please enter the total class size:');
// Initialization of the total number of persons meeting the conditions
var num = 0;
// Loop all students
for(var i = 0; i < sumNum; i++){
// Greater than or equal to 80 points
var score = prompt('Please enter the first' + (i + 1) +'The grades of one student:');
if(score >= 80){
num++;
}
}
//Output the percentage of students who fulfill the conditions
document.write('The percentage of students with scores greater than or equal to 80 is:' + num/sumNum)
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- Bananas are $3 a piece, oranges are $2 a piece, and strawberries are $1 a piece. Now you want to buy 100 fruits for $200, list all the possibilities in your browser.
<script>
// First method
// banana 0~100 number of bananas.
// orange 0~100 number of oranges.
// stawberry 0~100 number of strawberries
// banana * 3 + orange * 2 + strawberry * 1 = 200
// banana + orange + strawberry = 100
for(var banana = 0; banana <= 100; banana++){
for(var orange = 0; orange <= 100; orange++){
for(var strawberry = 0; strawberry <= 100; strawberry++){
if(banana * 3 + orange * 2 + strawberry * 1 == 200 && banana + orange + strawberry == 100){
document.write('You can buy' + banana + 'A banana;' + orange + 'An orange;' + strawberry + 'A strawberry; <br />')
}
}
}
}
/*
The second method
banana * 3 + orange * 2 + strawberry * 1 = 200
banana + orange + strawberry = 100
banana * 2 + orange = 100
orange = 100 - banana * 2
banana + 100 - banana * 2 + strawberry = 100
strawberry = banana
banana + strawberry = 100
banana <= 50 // cyclic condition (math.)
*/
var orange, strawberry;
// Likelihood of all bananas
for(var banana = 0; banana <= 50; banana++){
orange = 100 - banana * 2;
strawberry = banana;
document.write('You can buy' + banana + 'A banana;' + orange + 'An orange;' + strawberry + 'A strawberry; <br />')
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- Membership card four-digit sum, the first number is greater than 0, membership card four-digit sum is greater than 20 will rebate 50 yuan, otherwise no rebate.
<script>
// Enter the membership card prompt, and sum the four digits of the membership card over 20.
// Enter your membership card number first
// Take the top digit of a four-digit number in the ones, tens, hundreds, and thousands digits.
// var num = 2356;
// var q = parseInt(num / 1000); // thousands
// var b = parseInt((num - q * 1000)/100); // percentile
// var s = parseInt((num - q * 1000 - b * 100) / 10); // tenths
// var g = num - q * 1000 - b * 100 - s * 10; // everyone
// 2356/1000 2.356 parseInt(2.356)
// 2356-q*1000 356
// (g);
// (parseInt((num - q * 1000)/100)); // the expected value is 3
var cardNum = prompt('Please enter your membership card number:');
// Get the four digits
var q = parseInt(cardNum / 1000); // Thousands
var b = parseInt((cardNum - q * 1000)/100); // Hundredths
var s = parseInt((cardNum - q * 1000 - b * 100) / 10); // 10-bit
var g = cardNum - q * 1000 - b * 100 - s * 10; // Everyone
if(q + b + s + g > 20){
alert('Congratulations, you can get a $50 rebate!');
} else{
alert('Unfortunately, you do not fulfill the conditions for the rebate!')
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- Wage Income Tax The portion of wages over 3,000 is subject to personal income tax, outputting after-tax wages (tax rate of 0.05).
<script>
// Enter your salary
var pay = prompt('Enter your salary');
// Determine whether the conditions for payment of taxes have been met
if(pay > 3000){
// Calculate the actual salary you receive
// pay - (pay-3000) * 0.05
alert('The actual salary you received was:' + (pay - (pay-3000) * 0.05))
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- Users who purchase an item with one of the three items over $50 or a total of over $100 are eligible for a 15% discount, otherwise there is no discount.
<script>
// three items prompt one over $50, or total price over $100 conditions
// Enter the product
var goods1 = prompt('Please enter the price of the first item:') * 1;
var goods2 = prompt('Please enter the price of the second item:') * 1;
var goods3 = prompt('Please enter the price of the third item:') * 1;
if(goods1 > 50 || goods2 > 50 || goods3 > 50 || goods1 + goods2 + goods3 > 100){
alert('You need to pay:' + (goods1 + goods2 + goods3) * 0.85);
} else{
alert('You need to pay:' + (goods1 + goods2 + goods3));
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- Calculate the result of 1!+2!+3!+...+10!
<script>
// 1! 1 2! 2*1
// Calculate the factorial Calculate the factorial of 10 10! 10 * 9 *8 ... *1 Cumulative multiplication
var sum = 1;
for(var i = 1; i <= 4; i++){
sum *= i; // 1*1 1*1*2*3
}
// This is the sum of all factorials
var sumNum = 0;
// Cyclic factorial accumulation
for(var i = 1; i <= 10; i++){
// This is the value of each factorial
var sum = 1;
// add each factorial together when i is 1, 1!, when i is 2, 2!...
for(var j = 1; j <= i; j++){
sum *= j; // 1*1 1*1*2*3
}
// Accumulate each factorial
sumNum += sum;
}
alert(The result of '1!+2!+3!+...+10! is:' + sumNum);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- Outputs all four-digit integers that satisfy the following conditions. Condition: the single digit plus the hundredth digit is equal to the thousandth digit plus the tenth digit, and the four-digit number is odd.
<script>
// 1000 ~ 9999 Loop The first digit plus the hundredth digit equals the thousandth digit plus the tenth digit, and the four digits are odd Conditions
// var q = parseInt(cardNum / 1000); // thousands
// var b = parseInt((cardNum - q * 1000)/100); // percentile
// var s = parseInt((cardNum - q * 1000 - b * 100) / 10); // tenths
// var g = cardNum - q * 1000 - b * 100 - s * 10; // everyone
var q, b, s, g;
document.write('All four-digit integers that satisfy the following conditions <br>')
// // Find all four digits 1000 ~ 9999
for(var i = 1000; i <= 9999; i++){
q = parseInt(i / 1000); // Thousands
b = parseInt((i - q * 1000)/100); // Hundredths
s = parseInt((i - q * 1000 - b * 100) / 10); // 10-bit
g = i - q * 1000 - b * 100 - s * 10; // Everyone
// Determine if the first digit plus the hundredth digit equals the thousandth digit plus the tenth.
// The four digits are odd
if(g + b == q + s && i % 2 != 0){
document.write(i + '<br />')
}
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- Find all even sums between 1 and 10.
<script>
//1~10 Cycle Even Condition
// Variables that store sums that satisfy conditions
var sumNum = 0;
// Cycle 1 to 10
for (var i = 1; i <= 10; i++) {
//Is it an even number
if (i % 2 == 0) {
sumNum += i;
}
}
alert('The sum of all even numbers between 1 and 10 is:' + sumNum);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- Randomly enter a year, determine whether it is a leap year or a flat year, and tell us how many days there are in the month of February this year?
<script>
// Leap year: it is divisible by 400, or by 4, but not by 100.
var year = prompt('Please enter the year');
function isPrimeYear(year) { // year 2019
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
alert(year + 'It's the leap year');
return true;
} else {
alert(year + 'It's the year of peace')
return false;
}
}
// Calling Functions
// (isPrimeYear(year));
// Given a year, tell me how many days there are in February.
// February has 29 days if it's a leap year and 28 days if it's an equal year.
function getDays(year) { // year 2019
if (isPrimeYear(year)) { // year 2019
alert('There are 29 days in February this year');
} else {
alert('There are 28 days in February this year');
}
}
// Call the function getDays to get the number of days in February of the year.
getDays(year);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- Clock Case
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="clock"></div>
<! -- Load the js after loading is complete, reducing the amount of blank time on the page -->!
<script>
// Get the dom node
var clock1 = document.getElementById('clock');
// Encapsulated Functions
function clockFunc() {
// Get the current time
var date = new Date();
// year YY month MM date DD week dd hour hh minute mm second ss
// Get the year
var YY = date.getFullYear();
// Get the month.
var MM = date.getMonth() + 1;
// Get the date
var DD = date.getDate();
// Get the day of the week
var dd = date.getDay();
// Get hours
var hh = date.getHours();
// Get minutes
var mm = date.getMinutes();
// Get seconds
var ss = date.getSeconds();
// Formatting the day of the week
switch (dd) {
case 0:
dd = 'Sunday';
break;
case 1:
dd = 'Monday'
break;
case 2:
dd = 'Tuesday'
break;
case 3:
dd = 'Wednesday'
break;
case 4:
dd = 'Thursday'
break;
case 5:
dd = 'Friday'
break;
case 6:
dd = 'Saturday'
}
// Decimal
if (hh > 12) {
hh = ' PM ' + strFunc(hh - 12);
} else {
hh = ' AM ' + strFunc(hh);
}
// You want to add innerHTML to the tag whose id is clock.
// = "56565";
clock1.innerHTML = 'The current time is:' + YY + ' Years ' + MM + ' Months ' + DD + ' Day ' + dd + hh + ' : ' + strFunc(mm) + ' : ' + strFunc(ss);
}
// Functions that add zeros
function strFunc(num) {
if (num < 10) {
num = '0' + num;
}
return num;
}
// Timer
var timer = setInterval('clockFunc()', 1000);
</script>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
-
Enter the maximum value (min) and the minimum value (max) in a function, and return how many prime numbers are between the maximum and minimum values.
Idea: Write a function that determines whether a number is prime or not.
<script>
// Determine if a value is prime first. To determine if a value is prime, you need a formal parameter to pass the value into the function.
// If it's a prime number, return true.
function isPrimeNumber(num){
// prime number, a natural number divisible only by 1 and itself, 1 is not a prime number or a composite number
if(isNaN(num) || num <= 1){
return false;
} else{
// If flag is true, it is a prime number, otherwise, it is not a prime number.
// Initialize it as a prime number
var flag = true;
// 3 is divisible by 2, 4 determines if it is divisible by 2,3, 5 determines if it is divisible by 2,3,4
for(var i = 2; i < num; i++){ // 9,
// Determine if the number is prime
// If the value is divisible by any number other than 1 before it, then
// That means he's not a prime.
if(num % i == 0){
flag = false;
// alert('You are a prime number!')
}
}
return flag;
}
}
// To determine how many primes there are between the minimum and maximum values of straight
// Maximum value max Minimum value min
function getPrimeNum(min, max){
// A variable that holds the number of primes between min and max.
var sumNum = 0;
// Get all the numbers from min to max first.
for(var i = min; i <= max; i++){
// Determine if i is a prime number
if(isPrimeNumber(i)){ // isPrimeNumber(i) is either true or false
sumNum ++;
}
}
// Return the number of all primes between min and max to the function
return sumNum;
}
alert(getPrimeNum(1, 72));// How many prime numbers are there between 1 and 72?
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- Functions to encapsulate the Fibonacci series, you can query the value of the Fibonacci series of the first place is how much
<script>
// 1. Fibonacci sequence
function cci(n){ // nth
if(isNaN(n) || n < 1){
return n;
} else if(n <= 2){
return 1;
} else{
// Store the number of the nth term
var num;
// The number of the n-2nd term
var num1 = 1; // 1,2..
// The number of the n-1st term
var num2 = 1; // 2,3..
for(var i = 3; i <= n; i++){
// Get the number of the nth item
num = num1 + num2;
// Update the n-2 item by taking the contents of the n-1 item and assigning it to the n-2 item.
num1 = num2;
// Update the n-1 item, by assigning the contents of the original n item to the n-1 item.
num2 = num;
}
// The value of the nth term
return num;
}
}
alert(cci(7));//13
// 2. Recursion
function cci(n){
if(isNaN(n) || n < 1){
return n;
} else if(n <= 2){
return 1;
} else{
return cci(n-1) + cci(n-2);
}
}
alert(cci(7));//13
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- Write function validateCode(n), which implements the random generation of n-digit composition of the verification code, and return the code.
<script>
// Generate an n-digit CAPTCHA
// Return this CAPTCHA
function validateCode(n){
// Initialize the variable that holds the CAPTCHA
var str = '';
// n digits
for(var i=0; i<n; i++){
// Random number () 0~1
// You need 0~10 without 10 ()*10
// ()*10 This takes a decimal value and converts it to an integer.
// Round down (()*10)
// ((()*10));
str += Math.floor(Math.random()*10);
}
return str;
}
document.write(validateCode(5));// Randomized 5-digit CAPTCHA code
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- Output on the web page: Today is: XXXX XXXX XXXX XXXX Sunday X XXXX XX days until May Day 2021.
<script>
// Get the current time
var today = new Date();
// Get the year
var YY = today.getFullYear();
// Get the month, plus 1
var MM = today.getMonth() + 1;
// Get the date
var DD = today.getDate();
// Get the day of the week, 0-6.
var dd = today.getDay();
// Get the timestamp of the current time
var startTime = today.getTime();
// Formatting the day of the week
switch (dd) {
case 0:
dd = 'Sunday';
break;
case 1:
dd = 'Monday'
break;
case 2:
dd = 'Tuesday'
break;
case 3:
dd = 'Wednesday'
break;
case 4:
dd = 'Thursday'
break;
case 5:
dd = 'Friday'
break;
case 6:
dd = 'Saturday'
}
// how many days until May 1, 2021, get timestamps on both sides
// You can add parameters directly to new Date(parameter)
var endDate = new Date();
// Set the year to 2021
endDate.setFullYear(2021);
// Set the month to May, pass in 4.
endDate.setMonth(4);
// Set the date to the 1st
endDate.setDate(1);
// Get a timestamp for May 1, 2021
var endTime = endDate.getTime();
// Get the remaining time in milliseconds.
var leftTime = endTime - startTime;
var leftDays = leftTime / 1000 / 60 / 60 / 24;
document.write("Today is:" + YY + "Year." + MM + "Moon." + DD + "Day "+ dd +" May 1, 2021."+ leftDays +"Days.")
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- connect an array['bananas', 'pomegranate', 'tangerine', 'pears', 'love bite']is inverted to['love bite', 'pears', 'tangerine', 'pomegranate', 'bananas']
<script>
// First approach
var arr = ['Banana', 'Apple', 'Tangerine', 'Pear', 'Strawberry'];
// Create a new array to hold the reversed elements.
var arr1 = [];
// Traverse the array
for(var i=arr.length-1; i>=0; i--){
arr1.push(arr[i]);
}
console.log(arr1)
// Second approach
var arr = ['Banana', 'Apple', 'Tangerine', 'Pear', 'Strawberry'];
console.log(arr.reverse());
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- Create a new array MyArr and assign values 'A', 'B', 'C', create a new array MyArr2 and assign values 'J ', 'K', 'L', merge the arrays MyArr and MyArr2 into MyArr3, and output the data of MyArr3 to the page, delete the first element and the last element of MyArr3, and output MyArr3 to the page. element in MyArr3 and output MyArr3 data to the page.
<script>
var myArr = ['A','B','C'];
var myArr2 = ['J','K','L'];
// Create a new array
var myArr3 = [];
// Encapsulated Functions
function createArr(arr, newArr){
for(var i=0; i<arr.length; i++){
newArr.push(arr[i]);
}
}
// Iterate through the array myArr
// for(var i=0; i<; i++){
// (myArr[i]);
// }
createArr(myArr, myArr3);
// Iterate through the array myArr2
// for(var i=0; i<; i++){
// (myArr2[i]);
// }
createArr(myArr2, myArr3);
document.write(myArr3 + '<br />');
// Delete the first element
myArr3.shift();
// Delete the last element
myArr3.pop();
document.write(myArr3);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- Receive user-entered grades from 3 students in 7 courses using an array, then display each student's name, total grade and grade point average on a page with a list of grades less than 60
<script>
// Create an array to hold students
var stuList = [];
for(var i=1; i<=3; i++){
var stu = prompt('Please enter the first' + i +'Name of the student:', 'Li Lei');
// Splicing grades less than 60 into a string
var lowerScoreStr = '';
// Define a variable to store the total grade
var sumScore = 0;
for(var j=1; j<=4; j++){
var score = prompt('Please enter' + stu + 'First' + j +'Gate scores:', '80') * 1;
// Total grade per student
sumScore += score;
// Judging grades less than 60
if(score<60){
lowerScoreStr += 'Achievements' + j + "Yes." + score;
}
}
document.write(stu + ''The overall score is:'' + sumScore + ''The average grade point average is:'' + sumScore/4 + ''Scores, less than 60 are:'' + lowerScoreStr + '<br />')
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- Write a de-duplication program to remove duplicate elements from the array [1, 2, 6, 8, 1, 2, 66, 2, 12]
<script>
// Array de-duplication First method
// Array initialization
var arr = [1, 2, 6, 8, 1, 2, 2, 2, 66, 2, 12];
// Traverse the array
// 1 compares to all elements after 1
for (var i = 0; i < arr.length; i++) {
// i is compared with all elements after i i+1~-1
for (var j = i + 1; j < arr.length; j++) {
// Determine if the element is a duplicate
if (arr[i] == arr[j]) {
// After deleting 2, the following elements will be replaced.
// The element at this position is considered to have been compared.
// So the element you're replacing didn't make the call.
arr.splice(j, 1);
// It's just a matter of re-determining where it's been deleted.
j--;
}
}
}
console.log(arr);
// Second method
var arr = [1, 2, 6, 8, 1, 2, 2, 2, 66, 2, 12];
// For storing new arrays that have been de-duplicated.
var newArr = [];
// Traverse the array
for(var i=0; i<arr.length; i++){
// Determine if arr[i] exists in the new array.
if(newArr.indexOf(arr[i]) == -1){
// [1], i=1, [1, 2]; i=2
newArr.push(arr[i]);
}
}
console.log(newArr);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
-
Create a computer object, the object is required to have a brand, color, weight, model, but also can watch movies, play games, knocking code
This is achieved using each of the three methods of object creation taught today
<script>
// Create objects literally
/*
Syntax: var object name = {
property name: property value
};
*/
var computer = {
brand: 'Millet',
color: 'Space Gray',
weight: '2kg',
model: 'mipro15.6 enhanced',
justSo: function() {
alert('Computers can also watch movies, play games, and code.')
}
}
console.log(computer);
computer.justSo();
//-------------------------------------------------------------------------------------------------
// new Object
// Syntax: var object name = new Object(); var object name = new Object(); var object name = new Object()
var computer = new Object();
computer.brand = 'Millet';
computer.color = 'Space Gray';
computer.weight = '2kg';
computer.model = 'mipro15.6 enhanced';
computer.justSo = function() {
alert('Computers can also watch movies, play games, and code.')
}
console.log(computer);
computer.justSo();
//------------------------------------------------------------------------------------------------------
// Constructor
function Computer() {
this.brand = 'Millet';
this.color = 'Space Gray';
this.weight = '2kg';
this.model = 'mipro15.6 enhanced';
this.justSo = 'Computers can also watch movies, play games, and code.';
}
console.log(new Computer());
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
-
Create an object method, which defines two methods, namely
1. find the greatest common divisor of two arbitrary positive integers, a and c, the greatest number divisible by both a and c.
2. find the least common multiple of two arbitrary positive integers
<script>
var method = {
// highest common divisor
max: function(a, b){ // a, b formal parameter
// greatest common divisor, if 2, 6; 1~4
var min = Math.min(a, b);
// Find the maximum value of the loop min, 1~min
for(var i=min; i>0; i--){
// Determine if the number is divisible by both a and b.
if(a%i == 0 && b%i == 0){
return i;
}
}
},
// Minimum common multiple
min: function(a, b){
// 2, 3 is 6, 2, 6 is 6
var max = Math.max(a,b);
for(var i=max; i<=a*b; i++){
if(i%a == 0 && i%b == 0){
return i;
}
}
}
}
console.log(method.max(12, 18));//Maximum common divisor
console.log(method.min(12, 18));//Least common multiple
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- Create a Teaching Tool object, which is required to have teaching equipment, a student roster, and a random roll call program.
<script>
var tools = {
m: "Computer.",
stuList: ["Lee Ray.", "Lucy", "lily", "Han Mei Mei."],
rollCall: function() {
// arr[suoyin]
var random = Math.floor(Math.random() * tools.stuList.length);
// take the element arr[index value] of the array
console.log(tools.stuList[random]);
// using the object's properties or methods inside the object.
// You can use this.attribute name, e.g., the
}
}
tools.rollCall()
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
-
To count the results of a class, language, math, English, history, 10 people, I'm going to search for a person's name. I'm going to search for a person's name. Please output all his information on the page.
- First create an array to hold the student information.
- Then assign the elements of the array to an object containing the names and grades.
- Create a function that asks me to pass in a name. You return to me the information about the student (name and grade object).
<script>
var myClass = [];
for (var i = 0; i < 3; i++) {
var stuName = prompt('Please enter your name', 'Li Lei');
var stuC = prompt('Please enter a language score', '90');
var stuM = prompt('Please enter a math grade', '98');
var stuE = prompt('Please enter your English score', '89');
var stuH = prompt('Please enter historical grades', '99');
myClass.push({
stuName: stuName,
stuC: stuC,
stuM: stuM,
stuE: stuE,
stuH: stuH
})
}
Creating Functions
function searchStu(sName) {
// Determine if there is a flag for this person
var flag = false;
// Iterate through all the students
for (var i = 0; i < myClass.length; i++) {
// Determine if stuName is equal to the current student's name.
if (myClass[i].stuName == sName) {
// Return information about this student
flag = true;
return myClass[i];
}
}
// Determine if the person does not exist
if (!flag) {
return {
stuName: "No such person has been identified.
};
}
}
var obj = searchStu('lily');
for (key in obj) {
document.write(key + ":" + obj[key] + '<br />');
}
console.log(searchStu('lily'));
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- Create a function that determines whether an element is in this array or not
<script>
// Determine if an element is in an array, indexOf, lastIndexOf, some.
function judge(num, arr){ // The name of the function is something you can change yourself.
// if((num) != -1){
// return true;
// }
// return false;
return arr.some(function(item){
return item === num;
})
}
console.log(judge(1, [1,2,3]));//Judge whether 1 is in [1,2,3] or not, return true if it is.
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- Increases each digit in the array by 35% and returns a new array
<script>
// map function
// array name.map(function(item,index,array){})
//Returns the result of the operation following return in the anonymous function.
function changeArr(arr){
return arr.map(function(item){
return item * (1+0.35);
})
}
console.log(changeArr([1,3,6]));
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- Creates a function that determines whether the element 30 exists in the array and returns a boolean.
<script>
// some
// Syntax: array name.some(function(item, index, array){})
// If only one element of the array satisfies the condition after return, then true, otherwise false.
function judge(arr){
return arr.some(function(item){
return item === 30;
})
}
console.log(judge([10, 20, 40]));// not present in the array 30 false
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- Create a function that passes in a number and an ascending array, asks to insert that number into that array, ensures that the new array is still ascending, and then returns that new array
<script>
function sortFunc(num, arr) {
if (num > arr[arr.length - 1]) {
return arr.concat(num);
}
var newArr = arr.concat(num);
return newArr.sort(function(a, b) {
return a - b
});
}
console.log(sortFunc(5, [1, 6, 10]));//[1,5,6,10]
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
-
Create a function that takes the incoming array and converts it to a string, with each element using the
-
Connections.For example: pass array ["web", "h5", "javascript"], return "web-h5-javascript".
<script>
// join()
// Methods for converting arrays to strings
// Syntax: array.join(argument)
// The '-' parameter indicates that you want to concatenate the elements of the array into a string with '-' and output it.
// If the parameters are not filled in, the default is to connect them with commas.
function joinFunc(arr){
return arr.join('-');
}
console.log(joinFunc(["web", "h5", "javascript"]));//web-h5-javascript
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- Creates a function that looks up the elements between parameter a and parameter b in the incoming array and returns an array of them.
<script>
function search(arr, a, b) {
var min = Math.min(a, b);
var max = Math.max(a, b);
// filter
// Syntax: array name.filter(function(item, index, array){})
// If the array has elements that satisfy the condition following return in the function.
// then store them in a new array and return the new array
return arr.filter(function(item) {
return item >= min && item < max;
})
}
console.log(search([12, 10, 5, 8, 6], 6, 10));
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
-
Creates a function that converts an incoming string into a camelback.
For example, if you pass in the string 'hello-world', it returns helloWorld.
<script>
function myFun(arr) {
var arr1 = arr.split('-');
var arr2 = arr1.map(function(item, index) {
var b = item;
if (index != 0) {
var a = item.charAt(0).toUpperCase();
b = item.replace(item.charAt(0), a);
}
return b;
})
return arr2.join('')
}
console.log(myFun('hello-world'));
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
-
Create a function to extract parameters, (the name of the parameter and the number of parameters is not determined) The function is as follows.
Pass a url to the function, and return the arguments in the url as an object.
For example:url = '/?id=1&num=6&name=xxx';
Return it to an object in the following form { id: '1', num: '6', name: 'xxx' }
<script>
function getParams(url) {
// get the string after the question mark first
var index = url.indexOf('?');
//Intercept the string after the question mark, but without the question mark.
var str = url.substring(index + 1);
//The strings after the question mark are separated into arrays according to the & character.
var strArr = str.split('&');
// Create an empty object for storing parameter information.
var param = {};
// Iterate over the array strArr
for (var i = 0; i < strArr.length; i++) {
var index1 = strArr[i].indexOf('=');
var key = strArr[i].substring(0, index1);
var value = strArr[i].substring(index1 + 1);
param[key] = value;
}
// (param);
return param;
}
console.log(getParams('/?id=1&num=6&name=xxx'));
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- Create a function that finds the number of times the passed-in character appears in the passed-in string and concatenates the character and the number of times it appears into a string for return.
<script>
function getCount(char, str) { //(Characters, strings)
//Cut string into array, empty string cutting
var strArr = str.split('');
//Initialize the counter
var num = 0;
// Iterate through the array
for (var i = 0; i < strArr.length; i++) {
// Determine whether the string char is equal to the current character.
if (char === strArr[i]) {
// Counter self-increment
num++;
}
}
return char + num;
}
//calling a function
console.log(getCount('s', "aahhbbsnnbb"));
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
38. Random roll call
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#radm {
font-size: 150px;
text-align: center;
line-height: 800px;
font-weight: 400;
}
</style>
</head>
<body>
<div id="radm">commencement</div>
</body>
<script>
var arr = ['Xiaochu', 'Little Xin', 'Little Lee', 'Little Red', 'Little Zhang', 'Little Liu', 'Xiao Mei', 'Small picture', 'The Kid']
console.log(arr.length);
var radm = document.getElementById('radm');
var i = 0;
var time;
radm.onclick = function() {
i++;
if (i % 2 == 0) {
clearInterval(time)
} else {
time = setInterval(function() {
var k = Math.floor(Math.random() * arr.length);
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
radm.innerHTML = arr[k];
radm.style.color = `rgb(${r},${g},${b})`;
}, 30)
}
}
</script>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45