Bạn đang tìm bài tập JavaScript để rèn luyện kỹ năng và làm quen với những thử thách thực tế? Đây chính là “mảnh đất màu mỡ” để bạn vừa học vừa áp dụng ngay, từ đó tăng tốc con đường trở thành lập trình viên chuyên nghiệp. Đừng lo nếu bạn còn là “newbie”, những thử thách nhỏ sẽ giúp bạn vững vàng hơn từng bước. Và… hãy cùng CodeGym Đà Nẵng khám phá ở bài viết dưới đây!
JavaScript là gì?
JavaScript là một ngôn ngữ lập trình hướng đối tượng, có khả năng chạy trên nhiều nền tảng khác nhau. Đây là ngôn ngữ gọn nhẹ, linh hoạt và dễ tích hợp. Khi hoạt động trong môi trường host (như trình duyệt web), JavaScript có thể tương tác với các đối tượng của môi trường đó, giúp lập trình viên điều khiển chúng bằng mã lệnh.
Ngoài ra, JavaScript còn cung cấp thư viện chuẩn gồm nhiều đối tượng hữu ích như mảng, ngày tháng, toán học, cùng với các thành phần ngôn ngữ cơ bản như toán tử, cấu trúc điều khiển và câu lệnh.
JavaScript biến trang web tĩnh thành trải nghiệm sống động chỉ với vài dòng code (Nguồn: Internet)
Vì sao nên học JavaScript?
Khi học JavaScript, bạn không chỉ tiếp cận một ngôn ngữ phổ biến mà còn nhận về nhiều lợi ích thiết thực:
- Tương thích tốt với trình duyệt: JavaScript là ngôn ngữ “mặc định” của Internet, cho phép bạn dễ dàng viết, chạy và kiểm tra mã nguồn ngay trên trình duyệt. Chỉ cần một công cụ soạn thảo như VSCode hay Sublime Text, bạn đã có thể bắt tay vào lập trình ngay lập tức.
- Đa năng trong ứng dụng: Không chỉ phục vụ lập trình web, JavaScript còn được sử dụng rộng rãi ở nhiều lĩnh vực khác như Frontend, Backend, phát triển ứng dụng di động, game hay thậm chí cả lưu trữ dữ liệu trên nền tảng đám mây.
- Kho tài nguyên phong phú: Đây là ngôn ngữ có cộng đồng đông đảo và tài nguyên cực kỳ dồi dào. Bạn có thể tìm thấy vô số tài liệu, công cụ, giải pháp trên các nền tảng nổi tiếng như GitHub, GeeksforGeeks, StackOverflow hay Hashnode để luôn bắt kịp xu hướng công nghệ.
- Dễ tiếp cận cho người mới: JavaScript được đánh giá là ngôn ngữ thân thiện, dễ học, không đòi hỏi công cụ phức tạp và có thể chạy trực tiếp trong trình duyệt, rất phù hợp cho những ai mới bắt đầu hành trình lập trình.
- Mở rộng cơ hội nghề nghiệp: Việc thành thạo JavaScript giúp bạn gia tăng lợi thế cạnh tranh trong thị trường lao động. Bên cạnh đó, nếu nắm thêm các framework hiện đại như React.js hay Node.js, bạn sẽ có nhiều cơ hội thăng tiến và phát triển sự nghiệp hơn nữa.
Tổng hợp bài tập JavaScript cơ bản có đáp án
1. Hiển thị ngày và giờ hiện tại
Viết chương trình JavaScript hiển thị ngày và thời gian hệ thống theo định dạng mẫu.
Ví dụ: Hôm nay là Thứ Ba. Giờ hiện tại: 10 giờ tối : 30 : 38.
Code mẫu:
// Get the current date and time
var today = new Date();
// Get the day of the week (0-6, where 0 is Sunday and 6 is Saturday)
var day = today.getDay();
// Array of day names
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
// Display the current day
console.log("Today is: " + daylist[day] + ".");
// Get the current hour, minute, and second
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
// Determine if it's AM or PM
var prepand = (hour >= 12) ? " PM " : " AM ";
// Convert 24-hour format to 12-hour format
hour = (hour >= 12) ? hour - 12 : hour;
// Check for special cases when hour is 0
if (hour === 0 && prepand === ' PM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}
// Check for special cases when hour is 0
if (hour === 0 && prepand === ' AM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}
// Display the current time
console.log("Current Time: " + hour + prepand + " : " + minute + " : " + second);
2. In toàn bộ nội dung cửa sổ
Tạo chương trình JavaScript in ra nội dung trang web hiện tại.
Code mẫu:
// Define a function named print_current_page
function print_current_page() {
// Call the window.print() method to initiate the printing of the current page
window.print();
}
3. Lấy ngày hiện tại theo nhiều kiểu
Viết chương trình JavaScript lấy ngày hôm nay và hiển thị dưới các định dạng:
mm-dd-yyyy, mm/dd/yyyy, dd-mm-yyyy, dd/mm/yyyy.
Code mẫu:
// Get the current date var today = new Date(); // Get the day of the month var dd = today.getDate(); // Get the month (adding 1 because months are zero-based) var mm = today.getMonth() + 1; // Get the year var yyyy = today.getFullYear(); // Add leading zero if the day is less than 10 if (dd < 10) { dd = '0' + dd; } // Add leading zero if the month is less than 10 if (mm < 10) { mm = '0' + mm; } // Format the date as mm-dd-yyyy and log it today = mm + '-' + dd + '-' + yyyy; console.log(today); // Format the date as mm/dd/yyyy and log it today = mm + '/' + dd + '/' + yyyy; console.log(today); // Format the date as dd-mm-yyyy and log it today = dd + '-' + mm + '-' + yyyy; console.log(today); // Format the date as dd/mm/yyyy and log it today = dd + '/' + mm + '/' + yyyy; console.log(today);
4. Tính diện tích tam giác (cạnh 5, 6, 7)
Viết chương trình JavaScript tính diện tích tam giác với ba cạnh 5, 6, 7.
Code mẫu:
// Define the lengths of the three sides of a triangle
var side1 = 5;
var side2 = 6;
var side3 = 7;
// Calculate the semi-perimeter of the triangle
var s = (side1 + side2 + side3) / 2;
// Use Heron's formula to calculate the area of the triangle
var area = Math.sqrt(s * ((s - side1) * (s - side2) * (s - side3)));
// Log the calculated area to the console
console.log(area);
5. Xoay vòng chuỗi ‘w3resource’
Tạo chương trình JavaScript định kỳ xoay chuỗi bằng cách chuyển ký tự cuối lên đầu.
Code mẫu:
// Define a function that animates the characters of a string
function animate_string(id) {
// Get the HTML element by its id
var element = document.getElementById(id);
// Access the text node inside the element (assuming no other children)
var textNode = element.childNodes[0];
// Extract the initial text content of the text node
var text = textNode.data;
// Set up an interval to rotate the characters in the text every 100 milliseconds
setInterval(function () {
// Move the last character to the beginning of the string
text = text[text.length - 1] + text.substring(0, text.length - 1);
// Update the text content of the text node with the modified string
textNode.data = text;
}, 100);
}
6. Kiểm tra năm nhuận (theo lịch Gregory)
Viết hàm JavaScript xác định một năm có phải năm nhuận hay không.
Code mẫu:
// Define a function to check if a given year is a leap year
function leapyear(year) {
// Return true if the year is divisible by 4 but not divisible by 100 unless it's also divisible by 400
return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}
// Test the function with various years and log the results to the console
console.log(leapyear(2016)); // Expected output: true
console.log(leapyear(2000)); // Expected output: true
console.log(leapyear(1700)); // Expected output: false
console.log(leapyear(1800)); // Expected output: false
console.log(leapyear(100)); // Expected output: false
7. Tìm năm có ngày 1/1 là Chủ Nhật (2014–2050)
Lập trình JavaScript để kiểm tra những năm từ 2014 đến 2050 mà ngày 1/1 rơi vào Chủ Nhật.
Code mẫu:
// Log a separator to visually distinguish the output
console.log('--------------------');
// Loop through the years from 2014 to 2050 (inclusive)
for (var year = 2014; year <= 2050; year++) {
// Create a Date object for January 1st of the current year
var d = new Date(year, 0, 1);
// Check if January 1st is a Sunday (where Sunday corresponds to day index 0)
if (d.getDay() === 0) {
// Log a message if January 1st is a Sunday for the current year
console.log("1st January is being a Sunday " + year);
}
}
// Log another separator to conclude the output
console.log('--------------------');
8. Trò chơi đoán số
Chương trình JavaScript sinh số ngẫu nhiên từ 1 đến 10, người dùng nhập dự đoán. Đúng → báo “Tốt”, sai → báo “Không khớp”.
Code mẫu:
// Generate a random integer between 1 and 10 (inclusive)
var num = Math.ceil(Math.random() * 10);
// Log the generated random number to the console
console.log(num);
// Prompt the user to guess a number between 1 and 10 (inclusive)
var gnum = prompt('Guess the number between 1 and 10 inclusive');
// Check if the guessed number matches the generated random number
if (gnum == num)
// Log a message if the guessed number matches the random number
console.log('Matched');
else
// Log a message if the guessed number does not match, and also provide the correct number
console.log('Not matched, the number was ' + gnum);
9. Đếm ngày còn lại đến Giáng Sinh
Viết chương trình JavaScript tính số ngày còn lại trước Giáng Sinh.
Code mẫu:
// Get the current date
today = new Date();
// Create a Date object for Christmas of the current year
var cmas = new Date(today.getFullYear(), 11, 25);
// Check if the current date is after December 25th
if (today.getMonth() == 11 && today.getDate() > 25) {
// If true, set Christmas for the next year
cmas.setFullYear(cmas.getFullYear() + 1);
}
// Calculate the difference in days between today and Christmas
var one_day = 1000 * 60 * 60 * 24;
// Log the number of days left until Christmas to the console
console.log(Math.ceil((cmas.getTime() - today.getTime()) / (one_day)) +
" days left until Christmas!");
10. Tính nhân và chia (dữ liệu nhập từ người dùng)
Chương trình JavaScript cho phép nhập hai số rồi thực hiện phép nhân và chia.
Code mẫu:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JavaScript program to calculate multiplication and division of two numbers </title>
<style type="text/css">
body {margin: 30px;}
</style>
</head>
<body>
<form>
1st Number : <input type="text" id="firstNumber" /><br>
2nd Number: <input type="text" id="secondNumber" /><br>
<input type="button" onClick="multiplyBy()" Value="Multiply" />
<input type="button" onClick="divideBy()" Value="Divide" />
</form>
<p>The Result is : <br>
<span id = "result"></span>
</p>
</body>
</html>
11. Chuyển đổi nhiệt độ (C ↔ F)
Viết chương trình JavaScript chuyển đổi nhiệt độ giữa độ C và độ F.
Ví dụ:
60°C = 140°F
45°F = 7.22°C
Code mẫu:
// Define a function to convert Celsius to Fahrenheit
function cToF(celsius) {
// Store the input Celsius temperature in a variable
var cTemp = celsius;
// Calculate the equivalent Fahrenheit temperature
var cToFahr = cTemp * 9 / 5 + 32;
// Create a message string describing the conversion result
var message = cTemp + '\xB0C is ' + cToFahr + ' \xB0F.';
// Log the message to the console
console.log(message);
}
// Define a function to convert Fahrenheit to Celsius
function fToC(fahrenheit) {
// Store the input Fahrenheit temperature in a variable
var fTemp = fahrenheit;
// Calculate the equivalent Celsius temperature
var fToCel = (fTemp - 32) * 5 / 9;
// Create a message string describing the conversion result
var message = fTemp + '\xB0F is ' + fToCel + '\xB0C.';
// Log the message to the console
console.log(message);
}
// Call the cToF function with a Celsius temperature of 60
cToF(60);
// Call the fToC function with a Fahrenheit temperature of 45
fToC(45);
12. Lấy URL hiện tại của trang web
Chương trình JavaScript in ra URL của trang đang tải.
Code mẫu:
// Log the current website URL to the console
alert(document.URL);
13. Tạo biến với tên do người dùng định nghĩa
Viết chương trình JavaScript cho phép tạo biến bằng tên mà người dùng nhập vào.
Code mẫu:
// Declare a variable named var_name and assign it the string 'abcd'
var var_name = 'abcd';
// Declare a variable named n and assign it the number 120
var n = 120;
// Assign the value of n to the property named 'abcd' of the 'this' object
this[var_name] = n;
// Log the value of the property 'abcd' of the 'this' object to the console
console.log(this[var_name]);
14. Lấy phần mở rộng của tệp
Viết chương trình JavaScript xác định phần mở rộng (đuôi) của một file.
Code mẫu:
// Assign the string "system.php" to the variable filename
filename = "system.php";
// Log the result of extracting the file extension using split and pop to the console
console.log(filename.split('.').pop());
// Reassign the variable filename to the string "abc.js"
filename = "abc.js";
// Log the result of extracting the file extension using split and pop to the console
console.log(filename.split('.').pop());
15. Hiệu giữa số bất kỳ và 13
Viết chương trình JavaScript tính hiệu với 13. Nếu số lớn hơn 13 thì trả về gấp đôi hiệu tuyệt đối.
Code mẫu:
// Define a function named difference that takes a parameter n
function difference(n) {
// Check if n is less than or equal to 13
if (n <= 13) {
// If true, return the difference between 13 and n
return 13 - n;
} else {
// If false, return the double of the difference between n and 13
return (n - 13) * 2;
}
}
// Log the result of calling the difference function with the argument 32 to the console
console.log(difference(32));
// Log the result of calling the difference function with the argument 11 to the console
console.log(difference(11));
16. Tính tổng 2 số nguyên (gấp 3 nếu giống nhau)
Chương trình JavaScript cộng hai số nguyên. Nếu chúng bằng nhau thì nhân 3 tổng.
Code mẫu:
// Define a function named sumTriple that takes two parameters, x and y
function sumTriple(x, y) {
// Check if x is equal to y
if (x == y) {
// If true, return three times the sum of x and y
return 3 * (x + y);
} else {
// If false, return the sum of x and y
return (x + y);
}
}
// Log the result of calling the sumTriple function with the arguments 10 and 20 to the console
console.log(sumTriple(10, 20));
// Log the result of calling the sumTriple function with the arguments 10 and 10 to the console
console.log(sumTriple(10, 10));
17. Hiệu tuyệt đối với 19 (gấp 3 nếu >19)
Viết chương trình JavaScript tính hiệu tuyệt đối với 19. Nếu số >19 thì trả về gấp 3.
Code mẫu:
// Define a function named diff_num that takes a parameter n
function diff_num(n) {
// Check if n is less than or equal to 19
if (n <= 19) {
// If true, return the difference between 19 and n
return (19 - n);
} else {
// If false, return three times the difference between n and 19
return (n - 19) * 3;
}
}
// Log the result of calling the diff_num function with the argument 12 to the console
console.log(diff_num(12));
// Log the result of calling the diff_num function with the argument 19 to the console
console.log(diff_num(19));
// Log the result of calling the diff_num function with the argument 22 to the console
console.log(diff_num(22));
18. Kiểm tra số hoặc tổng bằng 50
Chương trình JavaScript trả về true nếu một số là 50 hoặc tổng của hai số bằng 50.
Code mẫu:
// Define a function named test50 that takes two parameters, x and y
function test50(x, y) {
// Return true if x is equal to 50 or y is equal to 50 or the sum of x and y is equal to 50; otherwise, return false
return ((x == 50 || y == 50) || (x + y == 50));
}
// Log the result of calling the test50 function with the arguments 50 and 50 to the console
console.log(test50(50, 50));
// Log the result of calling the test50 function with the arguments 20 and 50 to the console
console.log(test50(20, 50));
// Log the result of calling the test50 function with the arguments 20 and 20 to the console
console.log(test50(20, 20));
// Log the result of calling the test50 function with the arguments 20 and 30 to the console
console.log(test50(20, 30));
19. Kiểm tra số nguyên nằm trong khoảng 20 của 100 hoặc 400
Viết chương trình JavaScript để xem một số có nằm trong phạm vi ±20 của 100 hoặc 400 không.
Code mẫu:
// Define a function named testhundred that takes a parameter x
function testhundred(x) {
// Return true if the absolute difference between 100 and x is less than or equal to 20,
// or the absolute difference between 400 and x is less than or equal to 20; otherwise, return false
return ((Math.abs(100 - x) <= 20) || (Math.abs(400 - x) <= 20));
}
// Log the result of calling the testhundred function with the argument 10 to the console
console.log(testhundred(10));
// Log the result of calling the testhundred function with the argument 90 to the console
console.log(testhundred(90));
// Log the result of calling the testhundred function with the argument 99 to the console
console.log(testhundred(99));
// Log the result of calling the testhundred function with the argument 199 to the console
console.log(testhundred(199));
// Log the result of calling the testhundred function with the argument 200 to the console
console.log(testhundred(200));
20. Kiểm tra số nguyên dương và âm
Viết chương trình JavaScript để xác định trong hai số nguyên cho trước, một số là dương và số còn lại là âm.
Code mẫu:
// Define a function named positive_negative that takes two parameters, x and y
function positive_negative(x, y) {
// Check if either x is negative and y is positive, or x is positive and y is negative
if ((x < 0 && y > 0) || (x > 0 && y < 0)) {
// If true, return true
return true;
} else {
// If false, return false
return false;
}
}
// Log the result of calling the positive_negative function with the arguments 2 and 2 to the console
console.log(positive_negative(2, 2));
// Log the result of calling the positive_negative function with the arguments -2 and 2 to the console
console.log(positive_negative(-2, 2));
// Log the result of calling the positive_negative function with the arguments 2 and -2 to the console
console.log(positive_negative(2, -2));
// Log the result of calling the positive_negative function with the arguments -2 and -2 to the console
console.log(positive_negative(-2, -2));
21. Thêm tiền tố “Py” vào chuỗi
Viết chương trình JavaScript để thêm “Py” vào đầu chuỗi. Nếu chuỗi đã bắt đầu bằng “Py”, trả về chuỗi ban đầu.
Code mẫu:
// Define a function named string_check that takes a parameter str1
function string_check(str1) {
// Check if str1 is null, undefined, or starts with the substring 'Py'
if (str1 === null || str1 === undefined || str1.substring(0, 2) === 'Py') {
// If true, return str1
return str1;
}
// If false, prepend 'Py' to str1 and return the result
return "Py" + str1;
}
// Log the result of calling the string_check function with the argument "Python" to the console
console.log(string_check("Python"));
// Log the result of calling the string_check function with the argument "thon" to the console
console.log(string_check("thon"));
22. Xóa ký tự tại vị trí chỉ định
Viết chương trình JavaScript để loại bỏ ký tự ở một vị trí xác định trong chuỗi, sau đó trả về chuỗi mới.
Code mẫu:
// Define a function named remove_character that takes two parameters, str and char_pos
function remove_character(str, char_pos) {
// Extract the substring from the beginning of str up to (but not including) char_pos
part1 = str.substring(0, char_pos);
// Extract the substring from char_pos + 1 to the end of str
part2 = str.substring(char_pos + 1, str.length);
// Return the concatenation of part1 and part2, effectively removing the character at char_pos
return (part1 + part2);
}
// Log the result of calling the remove_character function with the arguments "Python" and 0 to the console
console.log(remove_character("Python", 0));
// Log the result of calling the remove_character function with the arguments "Python" and 3 to the console
console.log(remove_character("Python", 3));
// Log the result of calling the remove_character function with the arguments "Python" and 5 to the console
console.log(remove_character("Python", 5));
23. Đổi vị trí ký tự đầu và cuối
Viết chương trình JavaScript để tạo chuỗi mới bằng cách hoán đổi ký tự đầu tiên và cuối cùng. Yêu cầu độ dài chuỗi ≥ 1.
Code mẫu:
// Define a function named first_last that takes a parameter str1
function first_last(str1) {
// Check if the length of str1 is less than or equal to 1
if (str1.length <= 1) {
// If true, return str1 as is
return str1;
}
// Extract the substring from the second character to the second-to-last character of str1
mid_char = str1.substring(1, str1.length - 1);
// Return the last character of str1 followed by mid_char and then the first character of str1
return (str1.charAt(str1.length - 1)) + mid_char + str1.charAt(0);
}
// Log the result of calling the first_last function with the argument 'a' to the console
console.log(first_last('a'));
// Log the result of calling the first_last function with the argument 'ab' to the console
console.log(first_last('ab'));
// Log the result of calling the fi
rst_last function with the argument 'abc' to the console
console.log(first_last('abc'));
24. Thêm ký tự đầu vào trước và sau chuỗi
Viết chương trình JavaScript để lấy ký tự đầu tiên của chuỗi và chèn thêm vào cả đầu và cuối chuỗi.
Code mẫu:
// Define a function named front_back that takes a parameter str
function front_back(str) {
// Extract the first character of str
first = str.substring(0, 1);
// Return the concatenation of first, str, and first
return first + str + first;
}
// Log the result of calling the front_back function with the argument 'a' to the console
console.log(front_back('a'));
// Log the result of calling the front_back function with the argument 'ab' to the console
console.log(front_back('ab'));
// Log the result of calling the front_back function with the argument 'abc' to the console
console.log(front_back('abc'));
25. Kiểm tra bội số của 3 hoặc 7
Viết chương trình JavaScript để kiểm tra xem một số dương có phải bội số của 3 hoặc 7 hay không.
Code mẫu:
// Define a function named test37 that takes a parameter x
function test37(x) {
// Check if x is divisible by 3 or 7
if (x % 3 == 0 || x % 7 == 0) {
// If true, return true
return true;
}
// If not divisible by 3 or 7, return false
else {
return false;
}
}
// Log the result of calling the test37 function with the argument 12 to the console
console.log(test37(12));
// Log the result of calling the test37 function with the argument 14 to the console
console.log(test37(14));
// Log the result of calling the test37 function with the argument 10 to the console
console.log(test37(10));
// Log the result of calling the test37 function with the argument 11 to the console
console.log(test37(11));
26. Thêm 3 ký tự cuối vào đầu và cuối chuỗi
Viết chương trình JavaScript tạo chuỗi mới bằng cách lấy 3 ký tự cuối của chuỗi gốc rồi thêm vào cả hai đầu. Yêu cầu độ dài ≥ 3.
Code mẫu:
// Define a function named front_back3 that takes a parameter str
function front_back3(str) {
// Check if the length of str is greater than or equal to 3
if (str.length >= 3) {
// Set str_len to 3
str_len = 3;
// Extract the last three characters of str
back = str.substring(str.length - 3);
// Return the concatenation of back, str, and back
return back + str + back;
} else {
// If the length of str is less than 3, return false
return false;
}
}
// Log the result of calling the front_back3 function with the argument "abc" to the console
console.log(front_back3("abc"));
// Log the result of calling the front_back3 function with the argument "ab" to the console
console.log(front_back3("ab"));
// Log the result of calling the front_back3 function with the argument "abcd" to the console
console.log(front_back3("abcd"));
27. Chuỗi có bắt đầu bằng “Java” không
Viết chương trình JavaScript để kiểm tra một chuỗi có bắt đầu bằng từ “Java” hay không.
Code mẫu:
// Define a function named start_spec_str that takes a parameter str
function start_spec_str(str) {
// Check if the length of str is less than 4
if (str.length < 4) {
// If true, return false
return false;
}
// Extract the first four characters of str
front = str.substring(0, 4);
// Check if front is equal to 'Java'
if (front == 'Java') {
// If true, return true
return true;
} else {
// If not equal to 'Java', return false
return false;
}
}
// Log the result of calling the start_spec_str function with the argument "JavaScript" to the console
console.log(start_spec_str("JavaScript"));
// Log the result of calling the start_spec_str function with the argument "Java" to the console
console.log(start_spec_str("Java"));
// Log the result of calling the start_spec_str function with the argument "Python" to the console
console.log(start_spec_str("Python"));
28. Hai số nguyên trong khoảng 50–99
Viết chương trình JavaScript để kiểm tra xem hai số nguyên cho trước có thuộc phạm vi từ 50 đến 99 không. Trả về true nếu có ít nhất một số nằm trong khoảng.
Code mẫu:
// Define a function named check_numbers that takes two parameters x and y
function check_numbers(x, y) {
// Check if x or y is in the range between 50 and 99 (inclusive)
if ((x >= 50 && x <= 99) || (y >= 50 && y <= 99)) {
// If true, return true
return true;
} else {
// If not in the specified range, return false
return false;
}
}
// Log the result of calling the check_numbers function with the arguments 12 and 101 to the console
console.log(check_numbers(12, 101));
// Log the result of calling the check_numbers function with the arguments 52 and 80 to the console
console.log(check_numbers(52, 80));
// Log the result of calling the check_numbers function with the arguments 15 and 99 to the console
console.log(check_numbers(15, 99));
29. Ba số nguyên trong khoảng 50–99
Viết chương trình JavaScript để kiểm tra xem ba số nguyên cho trước có số nào nằm trong khoảng từ 50 đến 99 không.
Code mẫu:
// Define a function named check_three_nums that takes three parameters x, y, and z
function check_three_nums(x, y, z) {
// Check if at least one of the numbers is in the range between 50 and 99 (inclusive)
return (x >= 50 && x <= 99) || (y >= 50 && y <= 99) || (z >= 50 && z <= 99);
}
// Log the result of calling the check_three_nums function with the arguments 50, 90, and 99 to the console
console.log(check_three_nums(50, 90, 99));
// Log the result of calling the check_three_nums function with the arguments 5, 9, and 199 to the console
console.log(check_three_nums(5, 9, 199));
// Log the result of calling the check_three_nums function with the arguments 65, 89, and 199 to the console
console.log(check_three_nums(65, 89, 199));
// Log the result of calling the check_three_nums function with the arguments 65, 9, and 199 to the console
console.log(check_three_nums(65, 9, 199));
30. Xóa “Script” tại vị trí thứ 5
Viết chương trình JavaScript để kiểm tra xem “Script” có xuất hiện ở vị trí thứ 5 (chỉ mục 4) trong chuỗi không. Nếu có, trả về chuỗi loại bỏ phần “Script”, nếu không thì trả về chuỗi gốc.
Code mẫu:
// Define a function named check_script that takes a string parameter str
function check_script(str) {
// Check if the length of the string is less than 6
if (str.length < 6) {
// If true, return the original string as it is
return str;
}
// Initialize a variable result_str with the value of the input string
let result_str = str;
// Check if the substring from index 10 to index 4 (exclusive) is equal to 'Script'
if (str.substring(10, 4) == 'Script') {
// If true, update result_str to exclude the substring 'Script' from index 4 to the end
result_str = str.substring(0, 4) + str.substring(10, str.length);
}
// Return the final result_str
return result_str;
}
// Log the result of calling check_script with the argument "JavaScript" to the console
console.log(check_script("JavaScript"));
// Log the result of calling check_script with the argument "CoffeeScript" to the console
console.log(check_script("CoffeeScript"));
31. Tìm số lớn nhất trong ba số nguyên
Viết chương trình JavaScript để xác định số nguyên lớn nhất trong ba giá trị cho trước.
Code mẫu:
// Define a function named max_of_three that takes three parameters: x, y, and z
function max_of_three(x, y, z) {
// Initialize a variable max_val with the value 0
let max_val = 0;
// Check if x is greater than y
if (x > y) {
// If true, assign the value of x to max_val
max_val = x;
} else {
// If false, assign the value of y to max_val
max_val = y;
}
// Check if z is greater than max_val
if (z > max_val) {
// If true, update max_val to the value of z
max_val = z;
}
// Return the final value of max_val
return max_val;
}
// Log the result of calling max_of_three with the arguments 1, 0, 1 to the console
console.log(max_of_three(1, 0, 1));
// Log the result of calling max_of_three with the arguments 0, -10, -20 to the console
console.log(max_of_three(0, -10, -20));
// Log the result of calling max_of_three with the arguments 1000, 510, 440 to the console
console.log(max_of_three(1000, 510, 440));
32. Tìm giá trị gần 100 hơn
Viết chương trình JavaScript để so sánh hai số và trả về số nào gần 100 nhất.
Code mẫu:
// Define a function named near_100 with parameters x and y
function near_100(x, y) {
// Check if x is not equal to y
if (x != y) {
// Calculate the absolute difference between x and 100, store it in x1
x1 = Math.abs(x - 100);
// Calculate the absolute difference between y and 100, store it in y1
y1 = Math.abs(y - 100);
// Compare x1 and y1 to determine which value is closer to 100
if (x1 < y1) {
// Return x if x is closer to 100
return x;
}
// Return y if y is closer to 100
if (y1 < x1) {
return y;
}
// Return 0 if x and y are equidistant from 100
return 0;
} else {
// Return false if x is equal to y
return false;
}
}
// Log the result of calling near_100 with the arguments 90 and 89 to the console
console.log(near_100(90, 89));
// Log the result of calling near_100 with the arguments -90 and -89 to the console
console.log(near_100(-90, -89));
// Log the result of calling near_100 with the arguments 90 and 90 to the console
console.log(near_100(90, 90));
33. Kiểm tra hai số trong phạm vi nhất định
Viết chương trình JavaScript để kiểm tra xem cả hai số có cùng nằm trong khoảng 40..60 hoặc 70..100 hay không.
Code mẫu:
// Define a function named numbers_ranges with parameters x and y
function numbers_ranges(x, y) {
// Check if x and y fall within the first range (40 to 60) or the second range (70 to 100)
if ((x >= 40 && x <= 60 && y >= 40 && y <= 60) || (x >= 70 && x <= 100 && y >= 70 && y <= 100)) {
// Return true if the conditions are met
return true;
} else {
// Return false if the conditions are not met
return false;
}
}
// Log the result of calling numbers_ranges with the arguments 44 and 56 to the console
console.log(numbers_ranges(44, 56));
// Log the result of calling numbers_ranges with the arguments 70 and 95 to the console
console.log(numbers_ranges(70, 95));
// Log the result of calling numbers_ranges with the arguments 50 and 89 to the console
console.log(numbers_ranges(50, 89));
34. Số lớn hơn trong khoảng 40–60
Viết chương trình JavaScript để tìm số lớn nhất trong hai số nguyên dương nằm trong phạm vi 40 đến 60.
Code mẫu:
// Define a function named max_townums_range with parameters x and y
function max_townums_range(x, y) {
// Check if x and y fall within the specified range using logical AND and comparison operators
if (x >= 40 && x <= 60 && y >= 40 && y <= 60) {
// Check if x and y are the same
if (x === y) {
return "Numbers are the same";
} else if (x > y) {
return x; // Return x if it is greater than y
} else {
return y; // Return y if it is greater than x
}
} else {
return "Numbers don't fit in range"; // Return this message if numbers are outside the range
}
}
// Log the result of calling max_townums_range with the arguments 45 and 60 to the console
console.log(max_townums_range(45, 60));
// Log the result of calling max_townums_range with the arguments 25 and 60 to the console
console.log(max_townums_range(25, 60));
// Log the result of calling max_townums_range with the arguments 45 and 80 to the console
console.log(max_townums_range(45, 80));
35. Kiểm tra ký tự trong chuỗi
Viết chương trình JavaScript để xác định xem một ký tự cho trước có nằm trong khoảng từ vị trí thứ 2 đến thứ 4 của chuỗi hay không.
Code mẫu:
// Define a function named check_char with parameters str1 (a string) and char (a character)
function check_char(str1, char)
{
// Initialize a counter variable to 0
let ctr = 0;
// Use a for loop to iterate through each character in the string
for (let i = 0; i < str1.length; i++)
{
// Check if the current character is equal to the specified char and if the index is between 1 and 3 (inclusive)
if ((str1.charAt(i) == char) && (i >= 1 && i <= 3))
{
// Set the counter to 1 and break out of the loop
ctr = 1;
break;
}
}
// Check if the counter is 1 and return true, otherwise return false
if (ctr == 1) return true;
return false;
}
// Log the result of calling check_char with the arguments "Python" and "y" to the console
console.log(check_char("Python", "y"));
// Log the result of calling check_char with the arguments "JavaScript" and "a" to the console
console.log(check_char("JavaScript", "a"));
// Log the result of calling check_char with the arguments "Console" and "o" to the console
console.log(check_char("Console", "o"));
// Log the result of calling check_char with the arguments "Console" and "C" to the console
console.log(check_char("Console", "C"));
// Log the result of calling check_char with the arguments "Console" and "e" to the console
console.log(check_char("Console", "e"));
// Log the result of calling check_char with the arguments "JavaScript" and "S" to the console
console.log(check_char("JavaScript", "S"));
36. So sánh chữ số cuối cùng
Viết chương trình JavaScript để kiểm tra xem chữ số cuối cùng của ba số nguyên dương có giống nhau không.
Code mẫu:
// Define a function named last_digit with parameters x, y, and z
function last_digit(x, y, z) {
// Check if x, y, and z are greater than 0
if (x > 0 && y > 0 && z > 0) {
// Check if the last digits of x, y, and z are equal
return x % 10 === y % 10 && y % 10 === z % 10 && x % 10 === z % 10;
} else {
// If any of the numbers is not greater than 0, return false
return false;
}
}
// Log the result of calling last_digit with the arguments 20, 30, and 400 to the console
console.log(last_digit(20, 30, 400));
// Log the result of calling last_digit with the arguments -20, 30, and 400 to the console
console.log(last_digit(-20, 30, 400));
// Log the result of calling last_digit with the arguments 20, -30, and 400 to the console
console.log(last_digit(20, -30, 400));
// Log the result of calling last_digit with the arguments 20, 30, and -400 to the console
console.log(last_digit(20, 30, -400));
37. Sửa chuỗi theo độ dài
Viết chương trình JavaScript để tạo chuỗi mới: nếu chuỗi ≥ 3 ký tự thì 3 ký tự đầu được viết thường, nếu < 3 ký tự thì viết hoa toàn bộ.
Code mẫu:
// Define a function named upper_lower with parameter str
function upper_lower(str) {
// Check if the length of str is less than 3
if (str.length < 3) {
// If true, return the uppercase version of the entire string
return str.toUpperCase();
}
// Create a variable named front_part and store the lowercase version of the first 3 characters of str
front_part = (str.substring(0, 3)).toLowerCase();
// Create a variable named back_part and store the substring of str from index 3 to the end
back_part = str.substring(3, str.length);
// Return the concatenation of front_part and back_part
return front_part + back_part;
}
// Log the result of calling upper_lower with the argument "Python" to the console
console.log(upper_lower("Python"));
// Log the result of calling upper_lower with the argument "Py" to the console
console.log(upper_lower("Py"));
// Log the result of calling upper_lower with the argument "JAVAScript" to the console
console.log(upper_lower("JAVAScript"));
38. Đánh giá điểm số với bài kiểm tra cuối kỳ
Viết chương trình JavaScript để xét điểm học sinh dựa trên tổng điểm và điều kiện bài kiểm tra cuối kỳ.
- Nếu tổng điểm từ 89–100 → điểm A+.
- Nếu là bài cuối kỳ → chỉ đạt A+ khi tổng ≥ 90.
- Chương trình trả về ‘đúng’ nếu đạt A+, ngược lại ‘sai’.
Code mẫu:
// Define a function named exam_status with parameters totmarks and is_exam
function exam_status(totmarks, is_exam) {
// Check if is_exam is truthy (evaluates to true)
if (is_exam) {
// Return true if totmarks is greater than or equal to 90
return totmarks >= 90;
}
// Return true if totmarks is between 89 and 100 (inclusive)
return totmarks >= 89 && totmarks <= 100;
}
// Log the result of calling exam_status with arguments "78" and " " to the console
console.log(exam_status("78", " "));
// Log the result of calling exam_status with arguments "89" and "true " to the console
console.log(exam_status("89", "true "));
// Log the result of calling exam_status with arguments "99" and "true " to the console
console.log(exam_status("99", "true "));
39. Tổng hai số nguyên và trả về theo phạm vi
Viết chương trình JavaScript tính tổng của hai số nguyên: nếu tổng trong khoảng 50–80 → trả về 65, ngược lại trả về 80.
Code mẫu:
// Define a function named sortaSum with parameters x and y
function sortaSum(x, y)
{
// Calculate the sum of x and y and store it in the variable sum_nums
const sum_nums = x + y;
// Check if the sum_nums is between 50 and 80 (inclusive)
if (sum_nums >= 50 && sum_nums <= 80) {
// If true, return 65
return 65;
}
// If the condition is not met, return 80
return 80;
}
// Log the result of calling sortaSum with the arguments 30 and 20 to the console
console.log(sortaSum(30, 20));
// Log the result of calling sortaSum with the arguments 90 and 80 to the console
console.log(sortaSum(90, 80));
40. Kiểm tra số 8, tổng hoặc hiệu bằng 8
Viết chương trình JavaScript để xác định xem trong hai số nguyên, có số nào bằng 8 hoặc tổng/hiệu của chúng bằng 8.
Code mẫu:
// Define a function named check8 with parameters x and y
function check8(x, y) {
// Check if x or y is equal to 8
if (x == 8 || y == 8) {
// Return true if the condition is true
return true;
}
// Check if the sum of x and y is equal to 8 or the absolute difference between x and y is equal to 8
if (x + y == 8 || Math.abs(x - y) == 8) {
// Return true if the condition is true
return true;
}
// Return false if none of the conditions are met
return false;
}
// Log the result of calling check8 with the arguments 7 and 8 to the console
console.log(check8(7, 8));
// Log the result of calling check8 with the arguments 16 and 8 to the console
console.log(check8(16, 8));
// Log the result of calling check8 with the arguments 24 and 32 to the console
console.log(check8(24, 32));
// Log the result of calling check8 with the arguments 17 and 18 to the console
console.log(check8(17, 18));
41. Trả về 30, 40 hoặc 20 tùy theo số giống nhau
Viết chương trình JavaScript kiểm tra ba số nguyên:
- Nếu cả ba số giống nhau → trả về 30.
- Nếu chỉ hai số giống nhau → trả về 40.
- Nếu không số nào giống nhau → trả về 20.
Code mẫu:
// Define a function named three_numbers using function declaration with parameters x, y, and z
function three_numbers(x, y, z) {
// Check if x, y, and z are equal
if (x == y && y == z) {
return 30;
}
// Check if at least two of x, y, and z are equal
if (x == y || y == z || z == x) {
return 40;
}
// Return 20 if none of the conditions are met
return 20;
}
// Log the result of calling three_numbers with the arguments 8, 8, and 8 to the console
console.log(three_numbers(8, 8, 8));
// Log the result of calling three_numbers with the arguments 8, 8, and 18 to the console
console.log(three_numbers(8, 8, 18));
// Log the result of calling three_numbers with the arguments 8, 7, and 18 to the console
console.log(three_numbers(8, 7, 18));
42. Kiểm tra dãy tăng nghiêm ngặt hoặc tăng mềm
Viết chương trình JavaScript để xác định ba số có theo thứ tự tăng:
- Nghiêm ngặt: ví dụ 10, 15, 31.
- Mềm: cho phép số đứng trước bằng số sau, ví dụ 22, 22, 31.
Code mẫu:
// Define a function named number_order with parameters x, y, and z
function number_order(x, y, z) {
// Check if y is greater than x and z is greater than y
if (y > x && z > y) {
return "strict mode";
}
// Check if z is greater than y
else if (z > y) {
return "Soft mode";
}
// If none of the conditions are met, return "Undefined"
else {
return "Undefined";
}
}
// Log the result of calling number_order with the arguments 10, 15, and 31 to the console
console.log(number_order(10, 15, 31));
// Log the result of calling number_order with the arguments 24, 22, and 31 to the console
console.log(number_order(24, 22, 31));
// Log the result of calling number_order with the arguments 50, 21, and 15 to the console
console.log(number_order(50, 21, 15));
43. So sánh chữ số cuối của ba số
Viết chương trình JavaScript để kiểm tra trong ba số nguyên không âm, có ít nhất hai số có cùng chữ số tận cùng bên phải hay không.
Code mẫu:
// Define a function named same_last_digit with parameters p, q, and r
function same_last_digit(p, q, r) {
// Return true if the last digit of p is equal to the last digit of q or r,
// or if the last digit of q is equal to the last digit of r
return (p % 10 === q % 10) ||
(p % 10 === r % 10) ||
(q % 10 === r % 10);
}
// Log the result of calling same_last_digit with the arguments 22, 32, and 42 to the console
console.log(same_last_digit(22, 32, 42));
// Log the result of calling same_last_digit with the arguments 102, 302, and 2 to the console
console.log(same_last_digit(102, 302, 2));
// Log the result of calling same_last_digit with the arguments 20, 22, and 45 to the console
console.log(same_last_digit(20, 22, 45));
44. Kiểm tra số ≥20 và nhỏ hơn số khác
Viết chương trình JavaScript đánh giá ba số nguyên: xác định có số nào ≥20 và đồng thời nhỏ hơn ít nhất một số khác trong nhóm.
Code mẫu:
// Define a function named lessby20_others with parameters x, y, and z
function lessby20_others(x, y, z) {
// Check if x is greater than or equal to 20 and (x is less than y or x is less than z)
// Check if y is greater than or equal to 20 and (y is less than x or y is less than z)
// Check if z is greater than or equal to 20 and (z is less than y or z is less than x)
return (
(x >= 20 && (x < y || x < z)) ||
(y >= 20 && (y < x || y < z)) ||
(z >= 20 && (z < y || z < x))
);
}
// Log the result of calling lessby20_others with the arguments 23, 45, and 10 to the console
console.log(lessby20_others(23, 45, 10));
// Log the result of calling lessby20_others with the arguments 23, 23, and 10 to the console
console.log(lessby20_others(23, 23, 10));
// Log the result of calling lessby20_others with the arguments 21, 66, and 75 to the console
console.log(lessby20_others(21, 66, 75));
45. Kiểm tra số 15 hoặc tổng/hiệu bằng 15
Viết chương trình JavaScript để kiểm tra hai số nguyên: trả về true nếu một số bằng 15 hoặc tổng/hiệu của chúng bằng 15.
Code mẫu:
// Define a function named test_number with parameters x and y
function test_number(x, y) {
// Return true if x is equal to 15, y is equal to 15, the sum of x and y is equal to 15,
// or the absolute difference between x and y is equal to 15; otherwise, return false.
return (x === 15 || y === 15 || x + y === 15 || Math.abs(x - y) === 15);
}
// Log the result of calling test_number with the arguments 15 and 9 to the console
console.log(test_number(15, 9));
// Log the result of calling test_number with the arguments 25 and 15 to the console
console.log(test_number(25, 15));
// Log the result of calling test_number with the arguments 7 and 8 to the console
console.log(test_number(7, 8));
// Log the result of calling test_number with the arguments 25 and 10 to the console
console.log(test_number(25, 10));
// Log the result of calling test_number with the arguments 5 and 9 to the console
console.log(test_number(5, 9));
// Log the result of calling test_number with the arguments 7 and 9 to the console
console.log(test_number(7, 9));
// Log the result of calling test_number with the arguments 9 and 25 to the console
console.log(test_number(9, 25));
46. Một số là bội số của 7 hoặc 11
Viết chương trình JavaScript để xác định trong hai số nguyên không âm, chỉ duy nhất một số (không phải cả hai) là bội số của 7 hoặc 11.
Code mẫu:
// Define a function named valCheck with parameters a and b
function valCheck(a, b) {
// Check if the negation of the condition is true
if (!((a % 7 == 0 || a % 11 == 0) && (b % 7 == 0 || b % 11 == 0))) {
// Return true if either a is divisible by 7 or 11, or b is divisible by 7 or 11
return ((a % 7 == 0 || a % 11 == 0) || (b % 7 == 0 || b % 11 == 0));
}
else {
// If the negation of the condition is false, return false
return false;
}
}
// Log the result of calling valCheck with the arguments 14 and 21 to the console
console.log(valCheck(14, 21));
// Log the result of calling valCheck with the arguments 14 and 20 to the console
console.log(valCheck(14, 20));
// Log the result of calling valCheck with the arguments 16 and 20 to the console
console.log(valCheck(16, 20));
47. Kiểm tra số trong khoảng 40–10.000
Viết chương trình JavaScript để kiểm tra xem một số cho trước có thuộc phạm vi từ 40 đến 10.000 không.
Ví dụ: 40 hợp lệ, 4000 cũng hợp lệ.
Code mẫu:
// Define a function named test_digit with parameter n
function test_digit(n) {
// Check if n is less than 40 or greater than 10000
if (n < 40 || n > 10000)
// Return false if n is outside the specified range
return false;
else
// Check if n is between 40 and 10000 (inclusive)
if (n >= 40 && n <= 10000)
// Return true if n is within the specified range
return true;
}
// Log the result of calling test_digit with the arguments 40 to the console
console.log(test_digit(45));
// Log the result of calling test_digit with the arguments 79 to the console
console.log(test_digit(79));
// Log the result of calling test_digit with the arguments 30 to the console
console.log(test_digit(30));
48. Đảo ngược chuỗi
Viết chương trình JavaScript để nhận một chuỗi đầu vào và trả về chuỗi đảo ngược.
Code mẫu:
// Define a function named string_reverse with a parameter str
function string_reverse(str) {
// Split the string into an array of characters, reverse the order, and join them back into a string
return str.split("").reverse().join("");
}
// Log the result of calling string_reverse with the argument "w3resource" to the console
console.log(string_reverse("w3resource"));
// Log the result of calling string_reverse with the argument "www" to the console
console.log(string_reverse("www"));
// Log the result of calling string_reverse with the argument "JavaScript" to the console
console.log(string_reverse("JavaScript"));
49. Thay thế ký tự bằng chữ cái kế tiếp
Tạo chương trình JavaScript thay mọi ký tự trong chuỗi thành ký tự tiếp theo trong bảng chữ cái.
Code mẫu:
// Define a function named LetterChanges with parameter text
function LetterChanges(text) {
// Initialize an array by splitting the input text into individual characters
var s = text.split('');
// Iterate through each character in the array
for (var i = 0; i < s.length; i++) {
// Caesar cipher: Shift each character by one position in the alphabet
switch(s[i]) {
case ' ':
break;
case 'z':
s[i] = 'a';
break;
case 'Z':
s[i] = 'A';
break;
default:
s[i] = String.fromCharCode(1 + s[i].charCodeAt(0));
}
// Convert vowels to uppercase
switch(s[i]) {
case 'a': case 'e': case 'i': case 'o': case 'u':
s[i] = s[i].toUpperCase();
}
}
// Join the modified characters back into a string and return the result
return s.join('');
}
// Log the result of calling LetterChanges with the argument "PYTHON" to the console
console.log(LetterChanges("PYTHON"));
// Log the result of calling LetterChanges with the argument "W3R" to the console
console.log(LetterChanges("W3R"));
// Log the result of calling LetterChanges with the argument "php" to the console
console.log(LetterChanges("php"));
50. Viết hoa chữ cái đầu của mỗi từ
Viết chương trình JavaScript để in hoa ký tự đầu tiên của từng từ trong một chuỗi.
Code mẫu:
// Define a function named capital_letter with parameter str
function capital_letter(str)
{
// Split the input string into an array of words
str = str.split(" ");
// Iterate through each word in the array
for (var i = 0, x = str.length; i < x; i++) {
// Capitalize the first letter of each word and concatenate it with the rest of the word
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
// Join the modified array of words back into a string
return str.join(" ");
}
// Log the result of calling capital_letter with the given string to the console
console.log(capital_letter("Write a JavaScript program to capitalize the first letter of each word of a given string."));
51. Chuyển số thành giờ và phút
Tạo ứng dụng JavaScript đổi một số cho trước thành định dạng giờ và phút.
Code mẫu:
52. Sắp xếp chữ cái trong chuỗi theo alphabet
Viết chương trình JavaScript để sắp xếp các ký tự trong chuỗi theo thứ tự bảng chữ cái.
Code mẫu:
53. Kiểm tra ‘a’ và ‘b’ cách nhau 3 ký tự
Viết chương trình JavaScript kiểm tra xem trong chuỗi có cặp ký tự ‘a’ và ‘b’ cách nhau đúng 3 vị trí hay không.
Code mẫu:
54. Đếm nguyên âm trong chuỗi
Viết chương trình JavaScript để đếm số lượng nguyên âm có trong một chuỗi cho trước.
Code mẫu:
55. So sánh số lượng ký tự ‘p’ và ‘t’
Tạo chương trình JavaScript để kiểm tra xem chuỗi có chứa số lượng chữ ‘p’ và chữ ‘t’ bằng nhau không.
Code mẫu:
56. Chia số và định dạng dấu phẩy
Viết chương trình JavaScript chia hai số dương, sau đó trả về kết quả dưới dạng chuỗi có dấu phẩy phân tách.
Code mẫu:
57. Tạo chuỗi lặp lại nhiều lần
Viết chương trình JavaScript để tạo một chuỗi mới bằng cách nhân bản chuỗi gốc số lần cho trước.
Code mẫu:
58. Bốn lần lặp lại 3 ký tự cuối
Tạo chương trình JavaScript sinh ra chuỗi mới gồm 4 bản sao của 3 ký tự cuối chuỗi gốc (chuỗi phải dài ≥3).
Code mẫu:
59. Lấy nửa đầu của chuỗi có độ dài chẵn
Viết chương trình JavaScript để trích xuất nửa đầu từ một chuỗi có số ký tự chẵn.
Code mẫu:
60. Loại bỏ ký tự đầu và cuối chuỗi
Tạo chương trình JavaScript để trả về chuỗi mới không chứa ký tự đầu tiên và cuối cùng.
Code mẫu:
61. Ghép hai chuỗi bỏ ký tự đầu
Viết chương trình JavaScript nối hai chuỗi nhưng bỏ qua ký tự đầu tiên của mỗi chuỗi.
Code mẫu:
62. Đưa 3 ký tự cuối lên đầu chuỗi
Viết chương trình JavaScript dịch chuyển 3 ký tự cuối cùng của chuỗi lên đầu (chuỗi phải dài ≥3).
Code mẫu:
63. Trích xuất 3 ký tự giữa của chuỗi lẻ
Tạo chương trình JavaScript lấy ra 3 ký tự chính giữa từ chuỗi có độ dài lẻ (≥3).
Code mẫu:
64. Nối chuỗi có độ dài tương ứng
Viết chương trình JavaScript nối hai chuỗi, nếu độ dài không bằng nhau thì cắt bớt chuỗi dài hơn.
Code mẫu:
65. Kiểm tra chuỗi kết thúc bằng “Script”
Viết chương trình JavaScript để xác định chuỗi có kết thúc bằng “Script” hay không (chuỗi ≥6 ký tự).
Code mẫu:
66. Trả về tên thành phố bắt đầu bằng “Los” hoặc “New”
Viết chương trình JavaScript để hiển thị tên thành phố nếu chuỗi bắt đầu bằng “Los” hoặc “New”. Nếu không, trả về rỗng.
Code mẫu:
67. Xóa ký tự ‘P’ ở đầu/cuối chuỗi
Tạo chương trình JavaScript để loại bỏ ký tự ‘P’ nếu nó xuất hiện ở đầu hoặc cuối chuỗi. Nếu không, trả về chuỗi ban đầu.
Code mẫu:
68. Tạo chuỗi từ n ký tự đầu và cuối
Viết chương trình JavaScript để tạo chuỗi mới gồm n ký tự đầu tiên và n ký tự cuối cùng (chuỗi ≥ n).
Code mẫu:
69. Tổng của 3 phần tử trong mảng
Viết chương trình JavaScript tính tổng 3 phần tử của một mảng số nguyên có độ dài 3.
Code mẫu:
70. Xoay trái các phần tử mảng (3 phần tử)
Tạo chương trình JavaScript để xoay trái mảng số nguyên có độ dài 3.
Code mẫu:
71. Kiểm tra số 1 ở đầu hoặc cuối mảng
Viết chương trình JavaScript để kiểm tra xem số 1 có xuất hiện ở vị trí đầu tiên hoặc cuối cùng trong mảng không (mảng ≥1 phần tử).
Code mẫu:
72. So sánh phần tử đầu và cuối mảng
Tạo chương trình JavaScript để kiểm tra xem phần tử đầu tiên và cuối cùng của mảng có giống nhau không (mảng dài 3).
Code mẫu:
73. Đảo ngược mảng 3 phần tử
Viết chương trình JavaScript để đảo ngược thứ tự các phần tử trong mảng có độ dài 3.
Code mẫu:
74. Gán tất cả phần tử bằng giá trị lớn nhất (giữa đầu/cuối)
Viết chương trình JavaScript để so sánh phần tử đầu và cuối của mảng, lấy giá trị lớn hơn và gán cho toàn bộ phần tử.
Code mẫu:
75. Tạo mảng từ phần tử giữa của hai mảng
Viết chương trình JavaScript tạo mảng mới từ phần tử giữa của hai mảng số nguyên (mỗi mảng dài 3).
Code mẫu:
76. Tạo mảng từ phần tử đầu và cuối
Viết chương trình JavaScript để trả về mảng gồm phần tử đầu tiên và cuối cùng của một mảng cho trước (mảng ≥1).
Code mẫu:
77. Kiểm tra mảng có chứa 1 hay 3
Viết chương trình JavaScript để kiểm tra mảng (dài 2) có chứa số 1 hoặc số 3 hay không.
Code mẫu:
78. Kiểm tra mảng có chứa 1 hoặc 3
Tạo chương trình JavaScript để kiểm tra mảng dài 2 có phần tử bằng 1 hoặc 3.
Code mẫu:
79. Kiểm tra mảng chứa hai lần 30 và 40
Viết chương trình JavaScript để kiểm tra mảng số nguyên (dài ≤2) có chứa cả 30 và 40, mỗi số xuất hiện đúng 2 lần.
Code mẫu:
80. Hoán đổi phần tử đầu và cuối mảng
Tạo chương trình JavaScript để đổi chỗ phần tử đầu và cuối của mảng (mảng ≥1).
Code mẫu:
81. Cộng hai chữ số trong số có hai chữ số
Viết chương trình JavaScript để tính tổng của hai chữ số từ số nguyên dương có 2 chữ số.
Code mẫu:
82. Cộng hai số nguyên không nhớ
Tạo chương trình JavaScript để cộng hai số nguyên dương mà không thực hiện phép nhớ.
Code mẫu:
83. Tìm chuỗi dài nhất trong mảng
Viết chương trình JavaScript để tìm phần tử có độ dài lớn nhất trong một mảng chuỗi.
Code mẫu:
84. Thay thế ký tự bằng chữ cái kế tiếp (a→b, z→a)
Viết chương trình JavaScript thay mỗi ký tự trong chuỗi bằng chữ cái tiếp theo trong bảng chữ cái.
Code mẫu:
85. Tách mảng thành hai nhóm xen kẽ và tính tổng
Viết chương trình JavaScript chia một mảng thành hai nhóm xen kẽ, tính tổng từng nhóm rồi trả về mảng gồm 2 phần tử.
Code mẫu:
86. Xác định loại góc
Viết chương trình JavaScript phân loại góc theo số đo:
- Nhọn: 0–90°
- Vuông: 90°
- Tù: 90–180°
- Thẳng: 180°
Code mẫu:
87. Kiểm tra hai mảng đồng dạng bằng một phép hoán đổi
Viết chương trình JavaScript để xem hai mảng số nguyên có cùng độ dài có thể giống nhau nếu hoán đổi tối đa một cặp phần tử hay không.
Code mẫu:
88. Kiểm tra đồng dạng của hai số nguyên với ước số
Viết chương trình JavaScript để xác định hai số nguyên có đồng dạng hay không, dựa trên một ước số cho trước chia hết cả hai hoặc không chia hết số nào.
Code mẫu:
89. Thay thế ký hiệu $ để biểu thức đúng
Viết chương trình JavaScript để kiểm tra xem có thể thay $ trong biểu thức x $ y = z bằng +, -, * hoặc / để biểu thức đúng không.
Code mẫu:
90. Phần tử lớn thứ k trong mảng
Viết chương trình JavaScript tìm phần tử lớn thứ k trong mảng số nguyên.
Code mẫu:
91. Tổng lớn nhất của k phần tử liên tiếp
Tìm tổng lớn nhất của bất kỳ dãy k phần tử kề nhau trong mảng số nguyên dương.
Code mẫu:
92. Hiệu lớn nhất giữa hai phần tử liền kề
Xác định khoảng chênh lệch lớn nhất giữa các cặp phần tử kề nhau trong mảng.
Code mẫu:
93. Hiệu lớn nhất giữa mọi cặp phần tử
Tìm hiệu số lớn nhất có thể giữa hai phần tử bất kỳ trong mảng.
Code mẫu:
94. Phần tử xuất hiện nhiều nhất
Xác định giá trị xuất hiện với tần suất cao nhất trong mảng số nguyên.
Code mẫu:
95. Thay toàn bộ số bằng một giá trị chỉ định
Thay tất cả phần tử số trong mảng bằng một số cho trước.
Code mẫu:
96. Tổng các hiệu tuyệt đối liên tiếp
Tính tổng |a[i] − a[i−1]| cho toàn bộ mảng số nguyên.
Code mẫu:
97. Chuỗi ngắn nhất có thể thành palindrome (thêm ở cuối)
Tìm chuỗi ngắn nhất để khi thêm vào cuối chuỗi gốc sẽ biến nó thành palindrome.
Code mẫu:
98. Đổi ít ký tự nhất để toàn chuỗi viết hoa/thường
Biến chuỗi thành toàn chữ hoa hoặc toàn chữ thường với số ký tự thay đổi tối thiểu.
Code mẫu:
99. Sắp xếp lại ký tự để khớp chuỗi khác
Kiểm tra liệu có thể hoán vị ký tự của chuỗi A để trở thành chuỗi B hay không.
Code mẫu:
100. Hai mảng có phần tử chung
Kiểm tra hai mảng số nguyên đã sắp xếp có ít nhất một phần tử chung.
Code mẫu:
101. Chỉ chữ cái Latinh, không có hai hoa/thường liền kề
Xác minh chuỗi chỉ gồm chữ cái Latinh và không có hai chữ hoa hoặc hai chữ thường đứng cạnh nhau.
Code mẫu:
102. Đếm số nghịch thế trong mảng
Đếm số cặp (i, j) sao cho i < j và a[i] > a[j].
Code mẫu:
103. Lớn nhất sau khi xóa đúng một chữ số
Từ số nguyên dương, xóa đúng một chữ số để nhận số lớn nhất.
Code mẫu:
104. Cặp có hiệu tuyệt đối gần nhất ngưỡng k
Chọn hai phần tử sao cho |a − b| ≤ k và càng gần k càng tốt.
Code mẫu:
105. Đếm số lần thay bằng tổng chữ số đến khi còn 1 chữ số
Lặp thay n bằng tổng chữ số của n cho tới khi còn 1 chữ số; đếm số lần lặp.
Code mẫu:
106. Chia liên tiếp cho tới khi kết quả không còn nguyên
Chia số nguyên cho số nguyên khác chừng nào kết quả vẫn là số nguyên; trả về kết quả cuối.
Code mẫu:
107. Đếm cặp có tính chia hết (có thứ tự)
Đếm số cặp có thứ tự (x, y) trong mảng sao cho x chia hết y hoặc y chia hết x.
Code mẫu:
108. Tích vô hướng hai vector 3D
Tính dot product của hai vector 3 chiều cho trước.
Code mẫu:
109. Liệt kê số nguyên tố từ 1 đến n
Tạo mảng chứa tất cả số nguyên tố trong [1..n].
Code mẫu:
110. Đếm số chẵn trước khi gặp giá trị X lần đầu
Đếm bao nhiêu số chẵn xuất hiện trước lần đầu tiên thấy X trong mảng.
Code mẫu:
111. Tìm số khác biệt trong ba số (hai số trùng nhau)
Trong ba số có hai số bằng nhau, hãy trả về số còn lại.
Code mẫu:
112. Số lượng số 0 tận cùng của n!
Tính số chữ số 0 ở cuối khi viết giai thừa n theo hệ thập phân.
Code mẫu:
113. Tính n + n/2 + n/4 + … (chia lấy nguyên)
Cộng chuỗi n + ⌊n/2⌋ + ⌊n/4⌋ + … cho tới 0.
Code mẫu:
114. Chuỗi có phải câu đúng?
Kiểm tra chuỗi bắt đầu bằng chữ in hoa và kết thúc bằng dấu chấm.
Code mẫu:
115. Ma trận đường chéo
Kiểm tra ma trận vuông: mọi phần tử ngoài đường chéo chính đều bằng 0.
Code mẫu:
116. Thay ‘#’ để số chia hết cho 3
Với chuỗi gồm chữ số và một ‘#’, tìm mọi thay thế ‘#’ bằng chữ số để số kết quả chia hết cho 3.
Code mẫu:
117. Ma trận đơn vị
Kiểm tra ma trận có 1 trên đường chéo chính và 0 ở vị trí khác hay không.
Code mẫu:
118. Số nằm trong một khoảng cho trước
Kiểm tra số x có thuộc [l, r] hay không.
Code mẫu:
119. Các chữ số tăng dần
Kiểm tra các chữ số của số nguyên có tăng (không giảm) theo thứ tự trái→phải hay không.
Code mẫu:
120. Điểm nằm trong đường tròn
Cho tâm (x, y), bán kính r, kiểm tra điểm (a, b) có nằm trong hình tròn.
Code mẫu:
121. Ma trận tam giác dưới
Kiểm tra ma trận vuông: mọi phần tử phía trên đường chéo chính bằng 0.
Code mẫu:
122. Mảng tăng/giảm nghiêm ngặt
Xác định mảng có tăng strict hoặc giảm strict từ đầu tới cuối.
Code mẫu:
123. Hoán vị các số từ 1 đến n
Kiểm tra mảng có phải hoán vị của 1..n (không trùng, đủ phần tử) hay không.
Code mẫu:
124. Toán tử NOR hai giá trị boolean
Tính p NOR q (đúng khi và chỉ khi cả p và q đều sai).
Code mẫu:
125. Chuỗi dài nhất trong mảng chuỗi
Tìm phần tử có độ dài lớn nhất trong mảng string.
Code mẫu:
126. Số chẵn lớn nhất trong mảng
Trả về số chẵn lớn nhất từ mảng số nguyên.
Code mẫu:
127. Đảo thứ tự bit của số nguyên
Đảo ngược thứ tự bit (theo độ dài cố định) của một số nguyên.
Code mẫu:
128. Số “tròn” nhỏ nhất ≥ giá trị cho trước
Tìm số kết thúc bằng một/multiple số 0 nhỏ nhất nhưng không nhỏ hơn giá trị cho trước.
Code mẫu:
129. Nguyên tố nhỏ nhất > x
Tìm số nguyên tố nhỏ nhất lớn hơn một số x.
Code mẫu:
130. Đếm chữ số chẵn trong số
Đếm bao nhiêu chữ số chẵn trong biểu diễn thập phân của số nguyên.
Code mẫu:
131. Mảng tổng tiền tố (prefix sum)
Tạo mảng y sao cho y[i] = x[0] + … + x[i].
Code mẫu:
132. Các ước nguyên tố phân biệt
Liệt kê các thừa số nguyên tố khác nhau của một số nguyên.
Code mẫu:
133. Phân số đúng hay không đúng
Cho phân số dương a/b, kiểm tra a < b (đúng) hay a ≥ b (không đúng).
Code mẫu:
134. Ánh xạ chữ thường đảo bảng chữ cái
Biến a→z, b→y, …, m↔n, …, z→a cho toàn bộ chữ thường trong chuỗi.
Code mẫu:
135. Xóa ký tự lặp lại
Loại bỏ các ký tự xuất hiện nhiều lần, chỉ giữ mỗi ký tự một lần.
Code mẫu:
136. Thay chữ số đầu tiên bằng ‘$’
Trong chuỗi có ít nhất một chữ số, thay chữ số đầu tiên gặp được bằng ký tự ‘$’.
Code mẫu:
137. Trả về số nếu >15, ngược lại trả 15
Nếu n > 15 trả về n, không thì trả 15.
Code mẫu:
138. Đảo bit của số 16-bit không dấu
Đảo ngược thứ tự 16 bit của một giá trị không dấu.
Code mẫu:
139. Vị trí số “tròn” ngoài cùng bên phải
Tìm chỉ số của phần tử cuối cùng kết thúc bằng 0; nếu không có, trả 0.
Code mẫu:
140. Tất cả chữ số có giống nhau?
Kiểm tra mọi chữ số của số cho trước có cùng một giá trị.
Code mẫu:
141. Số phần tử chung của hai mảng
Đếm bao nhiêu phần tử xuất hiện trong cả hai mảng.
Code mẫu:
142. Rút gọn đường dẫn tuyệt đối kiểu Unix
Chuẩn hóa đường dẫn (xử lý ./..///) thành dạng tối giản.
Code mẫu:
143. Sắp xếp chuỗi theo độ dài tăng dần
Sắp xếp mảng chuỗi theo độ dài; giữ nguyên thứ tự tương đối khi độ dài bằng nhau.
Code mẫu:
144. Phân tách URL thành các phần
Tách URL thành protocol, host, domain, path…; đưa các phần vào mảng.
Code mẫu:
145. Tìm n lớn nhất sao cho 1+2+…+n ≤ X
Xác định n tối đa thỏa tổng dãy tự nhiên không vượt quá X.
Code mẫu:
146. Tổng lập phương từ 1 đến n
Tính 1³ + 2³ + … + n³.
Code mẫu:
147. Tổng các chữ số xuất hiện trong chuỗi
Cộng tất cả ký tự số (0–9) xuất hiện trong chuỗi.
Code mẫu:
148. Hoán đổi hai nửa mảng chẵn phần tử
Với mảng có độ dài chẵn, đổi chỗ nửa đầu và nửa sau.
Code mẫu:
149. Đảo kiểu chữ (hoa ↔ thường)
Chuyển toàn bộ chữ cái: hoa thành thường, thường thành hoa.
Code mẫu:
150. Hoán đổi từng cặp chữ số liền kề (độ dài chẵn)
Với số có số chữ số chẵn, đổi chỗ từng cặp chữ số cạnh nhau.
Code mẫu:
0 Lời bình