Module 03 · JavaScript Programming for Web ApplicationsWeb 应用 JavaScript 编程
Enhancing JavaScript Skills using JSFiddle使用 JSFiddle 提升 JavaScript 技能
Estimated Time: 60 minutes
预计时间:60 分钟
Introduction: 引言
This lab is designed to provide you with practical exercises to enhance your JavaScript programming skills using JS Fiddle. The focus is on solving real-world logical problems, encouraging you to think and write efficient code and execute them in JS Fiddle to see the Output. By the end of this lab, you will have improved your ability to implement solutions for varied scenarios and gained confidence in your coding abilities.
本实验室旨在通过使用 JS Fiddle 提供实际练习,以增强您的 JavaScript 编程技能。重点是解决现实世界的逻辑问题,鼓励您思考并编写高效的代码,并在 JS Fiddle 中执行以查看输出。在本实验室结束时,您将提高解决各种场景的能力,并增强您的编程信心。
Objective: 目标
- Develop problem-solving skills using JavaScript
使用 JavaScript 开发问题解决技能 - Practice writing and debugging logical programs
练习编写和调试逻辑程序 - Understand how to implement real-world solutions using loops, functions, and conditional logic
理解如何使用循环、函数和条件逻辑实现现实世界的解决方案 - Strengthen coding practices on platforms like JSFiddle
加强 JSFiddle 等平台上的编码实践
Exercise 1: Calculate total sales amount 练习 1:计算总销售额
Problem: 问题:
You are working for an online store. Your task is to write a JavaScript code snippet that calculates the total sales amount for a given set of sales transactions.
您正在为一家在线商店工作。您的任务是编写一个 JavaScript 代码片段,用于计算给定一系列销售交易的总销售额。
Input details: 输入细节:
- An array of objects representing sales transactions. Each object has the following properties:
表示销售交易的物体数组。每个对象具有以下属性:item: Name of the product (string)
产品名称(字符串)quantity: Number of units sold (integer)quantity: 销售单位数(整数)price: Price per unit (float)
单位价格(浮点数)
Output details: 输出详情:
- A single number representing the total sales amount
一个表示总销售额的单个数字
Steps to implement: 实施步骤:
- Define an array of sales transactions with at least 3 sample objects
定义一个包含至少 3 个示例对象的销售交易数组 - Write a function
calculateTotalSalesthat takes this array as input
编写一个函数calculateTotalSales,它接受此数组作为输入 - Use a loop to iterate through the array and calculate the total sales amount
使用循环遍历数组并计算总销售额 - Print the total sales amount to the console
打印总销售额到控制台
Click here to view hints
点击此处查看提示
- The
salesarray contains objects, each representing a sales transaction withitem,quantity, andpriceproperties.
Thesales数组包含对象,每个对象代表一笔销售交易,具有item、quantity和price属性。 - Use a loop to go through each object in the
salesarray.
遍历sales数组中的每个对象。 - For each object, multiply the
quantityby thepriceto get the total for that item.
对于每个对象,将quantity乘以price以获得该项目的总数。 - Accumulate the totals in a variable to get the overall sales amount.
将总额累计到变量中,以获取总销售额。 - Return the accumulated total and display it using
console.log.
返回累计总额,并使用console.log显示。
Click here to see the solution code
点击此处查看解决方案代码
const sales = [
{ item: "Laptop", quantity: 2, price: 800 },
{ item: "Monitor", quantity: 1, price: 150 },
{ item: "Mouse", quantity: 4, price: 25 }
];
function calculateTotalSales(sales) {
let total = 0;
for (let i = 0; i < sales.length; i++) {
total += sales[i].quantity * sales[i].price;
}
return total;
}
console.log("Total Sales Amount:", calculateTotalSales(sales));
Write the program on JSFiddle:
在 JSFiddle 上编写程序:
- Go to JSFiddle 前往 JSFiddle
- Write the code in the JavaScript section
编写 JavaScript 部分的代码 - Execute the program by clicking the
Runbutton and check the results in the console section
执行程序,点击Run按钮,并在控制台部分检查结果
The output of the code should appear as shown in the screenshot below.
代码输出应如图下截图所示。
Exercise 2: Generate an order receipt 练习 2:生成订单收据
Problem: 问题:
Write a JavaScript program that generates a receipt for a customer's order. The receipt should include each item's name, quantity, price, and total cost.
编写一个 JavaScript 程序,用于生成客户的订单收据。收据应包括每项商品的名称、数量、价格和总计金额。
Input details: 输入细节:
- An array of objects representing ordered items. Each object has:
一个表示有序项的对象数组。每个对象具有:item: Name of the product (string)
产品名称(字符串)quantity: Quantity ordered (integer)quantity: 订单数量(整数)price: Price per unit (float)
单位价格(浮点数)
Output details: 输出详情:
- A detailed receipt showing each item's details and the grand total
一份详细收据,显示每项商品的详细信息及总金额
Steps to implement: 实施步骤:
- Define an array of ordered items with at least 3 sample entries
定义一个包含至少 3 个样本条目的有序数组 - Write a function
generateReceiptthat takes this array as input
编写一个函数generateReceipt,它接受此数组作为输入 - Use a loop to iterate through the items and calculate the total for each item and the grand total
使用循环遍历项目并计算每个项目的总额和总总额 - Print the receipt in a formatted string
打印格式化的字符串收据
Click here to view hints
点击此处查看提示
- The
ordersarray contains objects, each withitem,quantity, andpriceproperties representing items ordered.orders数组包含对象,每个对象具有item、quantity和price属性,代表有序项。 - Use a loop to iterate through each object in the
ordersarray.
使用循环遍历orders数组中的每个对象。 - For each item, calculate the total by multiplying
quantityandprice.
对于每个项目,通过乘以quantity和price来计算总额。 - Accumulate the totals in a variable
grandTotal.
累计变量grandTotal中的总和。 - Print each item's details and total cost using a formatted string.
打印每个项目的详细信息及总成本,使用格式化字符串。 - Finally, print the grand total after iterating through the array.
最后,在遍历数组后打印总金额。
Click here to see the solution code
点击此处查看解决方案代码
const orders = [
{ item: "Espresso", quantity: 2, price: 3.5 },
{ item: "Latte", quantity: 3, price: 4.0 },
{ item: "Cappuccino", quantity: 1, price: 4.5 }
];
function generateReceipt(orders) {
let grandTotal = 0;
console.log("Receipt:");
console.log("----------------------");
for (let i = 0; i < orders.length; i++) {
const itemTotal = orders[i].quantity * orders[i].price;
grandTotal += itemTotal;
console.log(`${orders[i].item} - Quantity: ${orders[i].quantity}, Price: $${orders[i].price}, Total: $${itemTotal}`);
}
console.log("----------------------");
console.log(`Grand Total: $${grandTotal}`);
}
generateReceipt(orders);
Write the program on JSFiddle:
在 JSFiddle 上编写程序:
- Go to JSFiddle 前往 JSFiddle
- write the code in the JavaScript section
编写 JavaScript 部分的代码 - Execute the program by clicking the
Runbutton and check the results in the console section
执行程序,点击Run按钮,并在控制台部分检查结果
The output of the code should appear as shown in the screenshot below.
代码输出应如图下截图所示。
Exercise 3: Validate passwords 练习 3:验证密码
Problem: 问题:
Write a JavaScript program to validate a list of passwords. A password is valid if:
编写一个 JavaScript 程序以验证密码列表。密码有效条件如下:
- It contains only alphanumeric characters (letters and numbers)
它只包含字母数字字符(字母和数字) - It must be at least 8 characters long, but no more than 20 characters
长度至少为 8 个字符,但不超过 20 个字符
Input details: 输入细节:
- An array of passwords (strings)
一组密码(字符串)
Output details: 输出详情:
- A message indicating whether each password is valid or invalid
指示每个密码是否有效或无效的消息
Steps to implement: 实施步骤:
- Define an array of sample passwords
定义一个示例密码数组 - Write a function
validatePasswordsthat takes this array as input
编写一个函数validatePasswords,它接受此数组作为输入 - Use a loop to iterate through the passwords and check each against the validation criteria
使用循环遍历密码并检查每个密码是否符合验证标准 - Log whether each password is valid or invalid
记录每个密码是否有效或无效
Click here to view hints
点击此处查看提示
- The
passwordsarray contains strings that need to be validated based on the given rules.passwords数组包含需要根据给定规则进行验证的字符串。 - Use a regular expression to define the pattern for valid passwords. The pattern should allow only alphanumeric characters and be between 8 and 20 characters long.
使用正则表达式定义有效密码的模式。该模式应仅允许字母数字字符,且长度在 8 到 20 个字符之间。 - Use the
testmethod to check if each password matches the regular expression.
使用test方法检查每个密码是否与正则表达式匹配。 - Iterate over the
passwordsarray and log each password as either valid or invalid based on the result of the regex check.
遍历passwords数组,根据正则表达式检查结果将每个密码记录为有效或无效。
Click here to see the solution code
点击此处查看解决方案代码
const passwords = ["Password123", "short", "ValidPass123", "too_long_password_example", "12345"];
function validatePasswords(passwords) {
const regex = /^[a-zA-Z0-9]{8,20}$/;
for (let i = 0; i < passwords.length; i++) {
if (regex.test(passwords[i])) {
console.log(`${passwords[i]} is valid.`);
} else {
console.log(`${passwords[i]} is invalid.`);
}
}
}
validatePasswords(passwords);
Write the program on JSFiddle:
在 JSFiddle 上编写程序:
- Go to JSFiddle
前往 JSFiddle - write the code in the JavaScript section
编写 JavaScript 部分的代码 - Execute the program by clicking the
Runbutton and check the results in the console section
执行程序,点击Run按钮,并在控制台部分检查结果
The output of the code should appear as shown in the screenshot below.
代码输出应如图下截图所示。
Exercise 4: Track product stock levels 练习 4:跟踪产品库存水平
Problem: 问题:
You are working for an online retail company. Your task is to write a JavaScript program that tracks the stock levels of various products in the inventory. The program should check if a product is in stock and log an appropriate message.
您正在为一家在线零售公司工作。您的任务是编写一个 JavaScript 程序,用于跟踪库存中各种产品的库存水平。程序应检查产品是否有库存,并记录相应的消息。
Input details: 输入细节:
- An array of objects representing products. Each object contains:
一个表示产品的对象数组。每个对象包含:product: Name of the product (string)
产品名称(字符串)stock: Number of units available in stock (integer)stock: 库存中可用的单位数量(整数)
Output details: 输出详情:
- A message for each product indicating whether the product is in stock or out of stock.
每件产品都有一条消息,指示该产品是否库存充足或缺货。
Steps to implement: 实施步骤:
- Define an array of product objects with at least 3 sample products
定义一个包含至少 3 个样本产品的产品对象数组 - Write a function
checkStockLevelsthat takes this array as input
编写一个函数checkStockLevels,它接受此数组作为输入 - Use a loop to iterate through the array and check the stock level for each product
使用循环遍历数组并检查每个产品的库存水平 - Print a message indicating if the product is "In Stock" or "Out of Stock"
打印一条消息,指示产品是“有货”还是“缺货”
Click here to view hints
点击此处查看提示
- The
productsarray contains objects withproductandstockproperties.products数组包含具有product和stock属性的物体。 - Use a loop to iterate through the
productsarray and check the stock level for each product.
使用循环遍历products数组并检查每个产品的库存水平。 - If the stock is greater than 0, log "In Stock"; otherwise, log "Out of Stock".
如果库存大于 0,记录“有货”;否则,记录“缺货”。
Click here to see the solution code
点击此处查看解决方案代码
const products = [
{ product: "Laptop", stock: 5 },
{ product: "Headphones", stock: 0 },
{ product: "Smartphone", stock: 3 }
];
function checkStockLevels(products) {
for (let i = 0; i < products.length; i++) {
if (products[i].stock > 0) {
console.log(`${products[i].product} is In Stock.`);
} else {
console.log(`${products[i].product} is Out of Stock.`);
}
}
}
checkStockLevels(products);
Write the program on JSFiddle:
在 JSFiddle 上编写程序:
- Go to JSFiddle 前往 JSFiddle
- Write the code in the JavaScript section
编写 JavaScript 部分的代码 - Execute the program by clicking the
Runbutton and check the results in the console section
执行程序,点击Run按钮,并在控制台部分检查结果
The output of the code should appear as shown in the screenshot below.
代码输出应如图下截图所示。
Conclusion: 结论
Through these exercises, you have practiced solving intermediate-level problems using JavaScript. Each task focused on different aspects of logical thinking, from validation to string manipulation. Continue practicing similar challenges to further enhance your programming skills and confidence.
通过这些练习,你已经练习了使用 JavaScript 解决中级问题。每个任务都侧重于逻辑思考的不同方面,从验证到字符串操作。继续练习类似的挑战,以进一步提高你的编程技能和信心。