题目描述: 找出数组中的最大值
输入: [3, 9, 2, 5, 1]
输出: 9
JavaScript解答:
function findMaxValue(arr) {
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
const input = [3, 9, 2, 5, 1];
const output = findMaxValue(input);
console.log(output); // 输出: 9
题目描述: 判断一个数是否为素数
输入: 13
输出: true
JavaScript解答:
function isPrimeNumber(num) {
if (num <= 1) {
return false;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
const input = 13;
const output = isPrimeNumber(input);
console.log(output); // 输出: true
题目描述: 统计字符串中的单词数
输入: “Hello, World! Welcome to the JavaScript world.”
输出: 7
JavaScript解答:
function countWords(str) {
const words = str.split(' ');
return words.length;
}
const input = "Hello, World! Welcome to the JavaScript world.";
const output = countWords(input);
console.log(output); // 输出: 7
题目描述: 将数组中的元素按照升序排列
输入: [5, 2, 9, 1, 3]
输出: [1, 2, 3, 5, 9]
JavaScript解答:
function sortArray(arr) {
return arr.sort((a, b) => a - b);
}
const input = [5, 2, 9, 1, 3];
const output = sortArray(input);
console.log(output); // 输出: [1, 2, 3, 5, 9]
题目描述: 将字符串中的每个单词首字母大写
输入: “hello, world! welcome to the javascript world.”
输出: “Hello, World! Welcome To The Javascript World.”
JavaScript解答:
function capitalizeWords(str) {
const words = str.split(' ');
const capitalizedWords = words.map(word => word.charAt(0).toUpperCase() + word.slice(1));
return capitalizedWords.join(' ');
}
const input = "hello, world! welcome to the javascript world.";
const output = capitalizeWords(input);
console.log(output); // 输出: "Hello, World! Welcome To The Javascript World."