- 编写 JavaScript 程序实现 输出“九九乘法表”( 左下三角形形式 )。
<!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>
<script>
for(var i=1;i<=9;i++){
str='';
for(var j=1;j<=i;j++){
str+=j+"*"+i+"="+i*j+"\t";
}
console.log(str);
}
</script>
</body>
</html>
2.编写 JavaScript 程序,测试输入的数是否是素数。
<!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>
<script>
var num=17;
var flag=true;
if(num>=0){
if(num==1||num==0){
flag=false;
}else if(flag==2)
flag=true;
}else{
for(var i=2;i<Math.sqrt(num);i++){
if(num%i==0){
flag=false;
break;
}
}
}
console.log(flag);
</script>
</body>
</html>
3.编写函数 isAnagram(str1,str2)用来检查两个字符串是否互为变位词。变位词指不计顺序的情况下两个单词包含完全相同的字母,不多不少。比如“silent”和“listen”互为变位词。
<!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>
<script>
function isAnagram(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
str1 = str1.split('');
//将str1转为数组!
for (var i = 0; i < str2.length; i++) {
var index = str1.indexOf(str2[i]);
if (index === -1) {
return false;
} else {
str1.splice(index, 1);
}
}
return str1.length === 0;
}
console.log(isAnagram("listen", "slient"));
</script>
</body>
</html>
4.编写函数 checkPalindrome(str)判断字符串 str 是否为回文字符串。如果一个字符串从前往后读和从后往前读是一样的,那么它就是一个回文字符串。例如,“mom”、“dad”以及“noon”都是回文字符串。如,checkPalinadrome("mom")结果为 true。
<!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>
<script>
function checkPalindrome(str){
var flag=true;
str=str.split('');
for(var i=0;i<str.length;i++){
if(i==str.length-1-i)
break;
if(str[i]!=str[str.length-i-1]){
flag=false;
break;
}
}
return flag;
}
console.log(checkPalindrome("mom"));
</script>
</body>
</html>
5. 编写 Javascript 程序,找出符合条件的数。
(1)页面的标题是“找出符合条件的数”
(2)页面内容:3 号标题显示“找出 1000 ~ 9999 之间能够被 17和 13 同时整除的整数、个数、累加和”。
(2)输出格式:每行 10 个整数。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>找出符合条件的数</title>
</head>
<body>
<h3>找出 1000 ~ 9999 之间能够被 17和 13 同时整除的整数、个数、累加和</h3>
</body>
<script>
let cnt=0;
let sum=0;
document.write("区间中符合条件的数有:<br />");
for(let i=1000;i<=9999;i++){
if(i%13==0&&i%17==0){
document.write(i+" ");
cnt++;
sum+=i;
if(cnt%10==0)
document.write('<br />');
}
}
document.write(`<br />区间中符合条件的数共有${cnt}个`);
document.write(`<br/>累加和为${sum}<br/>`)
</script>
</html>
6.利用 Date 对象编写程序,判断并输出今天是开学的第几周,星期几。
<!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>
<script>
function calculateWeekday(startDate) {
const today = new Date();
const timeDiff = today.getTime() - startDate.getTime();
const totalDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
const weeks = Math.floor(totalDays / 7) + 1;
const days = today.getDay();
return `今天是开学后的第 ${weeks} 周,星期${days} `;
}
const startDate = new Date(2023, 8, 16);
const result = calculateWeekday(startDate);
console.log(result);
</script>
</body>
</html>
7. 设计一个网页,输入一串用英文逗号分隔的数字字符串。编写程序,输出找出该组数中的最大、最小值、和 。并按从大到小排序后的输出结果(以逗号分隔)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数字处理</title>
</head>
<body>
<label for="numbers">输入一串数字(用英文逗号分隔):</label>
<input type="text" id="numbers">
<button onclick="processNumbers()">处理</button>
<p>最大值: <span id="maxValue"></span></p>
<p>最小值: <span id="minValue"></span></p>
<p>总和: <span id="sumValue"></span></p>
<p>排序结果: <span id="sortedResult"></span></p>
<script>
function processNumbers() {
const numbersInput = document.getElementById('numbers');
const numbersArray = numbersInput.value.split(',').map(num => parseInt(num.trim(), 10));
const maxValue = Math.max(...numbersArray);
const minValue = Math.min(...numbersArray);
const sumValue = numbersArray.reduce((acc, curr) => acc + curr, 0);
const sortedResult = numbersArray.sort((a, b) => b - a).join(', ');
document.getElementById('maxValue').innerText = maxValue;
document.getElementById('minValue').innerText = minValue;
document.getElementById('sumValue').innerText = sumValue;
document.getElementById('sortedResult').innerText = sortedResult;
}
</script>
</body>
</html>
8.要求用户在文本框中年份,点击判断按钮,用 alert 函数输出该年是否是闰年的结果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>判断闰年</title>
</head>
<body>
<input type="text" name="txtYear" id="txtyear" >
<input type="button" value="判断" onclick="testLeapYear()">
<script>
function testLeapYear(){
// 获取用户输入的年份
const yearInput = document.getElementById('txtyear');
const year = parseInt(yearInput.value);
// 判断是否为闰年
const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
// 显示结果
const resultMessage = isLeapYear ? `${year}年是闰年!` : `${year}年不是闰年。`;
alert(resultMessage);
}
</script>
</body>
</html>
9.直接使用 Javascript 的计时器、DOM 模型操作,将当前目录下的 10 张图片循环显示在网页上。
<!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>
<img id="displayedImage" src="" alt="image">
<script>
let currentIndex = 1;
const totalImages = 10;
function displayNextImage() {
const imageElement = document.getElementById('displayedImage');
const imagePath = `./image/image${currentIndex}.jpg`;
imageElement.src = imagePath;
currentIndex = (currentIndex % totalImages) + 1;
setTimeout(displayNextImage, 2000);
}
window.onload = function() {
displayNextImage();
};
</script>
</body>
</html>
10.制作“随机密码生成”程序,完成如图 1 所示界面,JavaScript 编程实现“生成密码”的功能。密码长度为:1~16 位,密码数量:1~10 个。
<!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>
table {
border-collapse: collapse;
font-size: 12px;
width: 400px;
height: 350px;
}
td{
border: 1px solid gray;
padding: 8px;
}
#bt{
background-color:cyan;
color: white;
border: 0;
}
#paichutext{
background-color:darkgray;
border: 1px solid gray;
}
#otherchar{
width: 45px;
background-color: darkgrey;
border: 1px solid gray;
}
</style>
</head>
<body>
<table border="1" >
<tr>
<td style="background-color:darkgray;">所用字符</td>
<td colspan="3">
<input type="checkbox" name="need" id="az">a-z
<input type="checkbox" name="need" id="AZ">A-Z
<input type="checkbox" name="need" id="09">0-9
<input type="checkbox" name="need" id="oz">
<input type="text" id="otherchar" value="!@#$%">
</td>
</tr>
<tr>
<td style="background-color:darkgray;">排除字符</td>
<td colspan="3">
<input type="checkbox" id="paichu">
<input type="text" id="paichutext" value="illo0O">
</td>
</tr>
<tr>
<td style="background-color:darkgray;">密码长度</td>
<td>
<select id="selen" >
<option value="len1">1</option>
<option value="len2">2</option>
<option value="len3">3</option>
<option value="len4">4</option>
<option value="len5">5</option>
<option value="len6">6</option>
<option value="len7">7</option>
<option value="len8">8</option>
<option value="len9">9</option>
<option value="len10">10</option>
<option value="len11">11</option>
<option value="len12">12</option>
<option value="len13">13</option>
<option value="len14">14</option>
<option value="len15">15</option>
<option value="len16">16</option>
</select>
位
</td>
<td style="background-color:darkgray;">密码数量</td>
<td>
<select id="secnt" >
<option value="op1">1</option>
<option value="op2">2</option>
<option value="op3">3</option>
<option value="op4">4</option>
<option value="op5">5</option>
<option value="op6">6</option>
<option value="op7">7</option>
<option value="op8">8</option>
<option value="op9">9</option>
<option value="op10">10</option>
</select>
个
</td>
</tr>
<tr>
<td colspan="4" align="center">
<button id="bt" onclick="generatepasswd()">生成密码</button></td>
</tr>
<tr>
<td colspan="4" align="center" >
<textarea id="textarea" style="height: 70px;">
</textarea>
</td>
</tr>
</table>
<script>
function generatepasswd(){
var len= document.getElementById("selen");
var lenop=len.options[len.selectedIndex].text;
var numlen=parseInt(lenop);
var cnt= document.getElementById("secnt");
var cntop=cnt.options[cnt.selectedIndex].text;
var numcnt=parseInt(cntop);
const lowercaseChars = 'abcdefghijklmnopqrstuvwxyz';
const uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numberChars = '0123456789';
const otherChars=document.getElementById("otherchar").value;
const paichuChars=document.getElementById("paichutext").value;
let allChars='';
let passwd='';
if(document.getElementById('az').checked){
allChars+=lowercaseChars;
}
if(document.getElementById('AZ').checked){
allChars+=uppercaseChars;
}
if(document.getElementById('09').checked){
allChars+=numberChars;
}
if(document.getElementById('oz').checked){
allChars+=otherChars;
}
if(document.getElementById('paichu').checked){
allChars= allChars.replace(new RegExp('[' + paichuChars + ']', 'g'), '');
}
console.log(otherChars);
console.log(paichuChars);
var val=document.getElementById("textarea");
for(let i=0;i<numcnt;i++){
passwd='';
for (let j= 0; j< numlen;j++) {
const randomIndex = Math.floor(Math.random() * allChars.length);
passwd += allChars.charAt(randomIndex);
}
val.value += passwd+'\n';
}
}
</script>
</body>
</html>
11. 使用 JavaScript 和 HTML 设计一个简单的整数四则运算测试程序(如图 2 所示),要求实现以下功能:
(1) 用户可以在页面上选择题目类型和题目数量。
(2) 用户单击“开始答题”按钮来开始答题。
(3) 页面上需要显示题目和用户的答案。
(4) 单击“提交答案”按钮来提交答案,系统显示用户得分。
<!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>
#quiz-container {
margin: 20px;
}
.question-container {
margin-bottom: 10px;
padding: 5px;
}
.correct {
background-color: green;
}
.incorrect {
background-color: red;
}
</style>
</head>
<body>
<h2>整数四则运算测试</h2>
<p>
题目类型:
<select id="question_type">
<option value="add">加法</option>
<option value="reduce">减法</option>
<option value="mul">乘法</option>
<option value="chu">除法</option>
</select>
</p>
<p>
题目数量:
<input type="number" id="question_number" min="1">
</p>
<p>
<button id="start" onclick="startQuiz()">开始答题</button>
<button id="submit" onclick="submitAnswers()" >提交答案</button>
</p>
<div id="quiz"></div>
<div id="score"></div>
<script>
let currentQuestion = 0;
let score = 0;
let questions = [];
function startQuiz(){
currentQuestion = 0;
score = 0;
questions = generateQuestions();
showQuestions();
};
function generateQuestions(){
questionType=document.getElementById('question_type').value;
questionNumber=document.getElementById('question_number').value;
const generatedQuestions = [];
for (let i = 0; i < questionNumber; i++) {
const num1 = Math.floor(Math.random() * 10);
const num2 = Math.floor(Math.random() * 10);
switch (questionType) {
case 'add':
correctAnswer = num1 + num2;
generatedQuestions.push({
question: `${num1} + ${num2} = `,
correctAnswer: correctAnswer.toString(),
userAnswer: ''
});
break;
case 'reduce':
correctAnswer = num1 - num2;
generatedQuestions.push({
question: `${num1} - ${num2} = `,
correctAnswer: correctAnswer.toString(),
userAnswer: ''
});
break;
case 'mul':
correctAnswer = num1 * num2;
generatedQuestions.push({
question: `${num1} * ${num2} = `,
correctAnswer: correctAnswer.toString(),
userAnswer: ''
});
break;
case 'chu':
correctAnswer = num1 /num2;
generatedQuestions.push({
question: `${num1} / ${num2} = `,
correctAnswer: correctAnswer.toString(),
userAnswer: ''
});
break;
}
}
return generatedQuestions;
}
function showQuestions() {
const quizContainer = document.getElementById('quiz');
quizContainer.innerHTML = '';
for (let i = 0; i < questions.length; i++) {
const questionContainer = document.createElement('div');
questionContainer.className = 'question-container';
questionContainer.innerHTML = `${questions[i].question} <input type="text" id="answer${i}" onchange="updateUserAnswer(${i})">`;
quizContainer.appendChild(questionContainer);
}
}
function updateUserAnswer(index) {
questions[index].userAnswer = document.getElementById(`answer${index}`).value;
}
function submitAnswers() {
for (let i = 0; i < questions.length; i++) {
const questionContainer = document.querySelector(`#quiz .question-container:nth-child(${i + 1})`);
if (questions[i].userAnswer === questions[i].correctAnswer) {
questionContainer.classList.add('correct');
score++;
} else {
questionContainer.classList.add('incorrect');
}
}
showScore();
}
function showScore() {
const scoreContainer = document.getElementById('score');
scoreContainer.innerHTML = `得分: ${score} / ${questions.length}`;
}
</script>
</body>
</html>