但说真的主要自己有两个认知盲区
1、不知道需要node.js这个运行环境
2、自己也没那个能力写调用文件
现在把代码全部帖上来以作纪念
第一个文件plays.json
{
"hamlet": { "name": "Hamlet", "type": "tragedy" },
"as-like": { "name": "As You Like It", "type": "comedy" },
"othello": { "name": "Othello", "type": "tragedy" }
}
第二个文件invoice.json
{
"customer": "BigCo",
"performances": [
{ "playId": "hamlet", "audience": 55 },
{ "playId": "as-like", "audience": 35 },
{ "playId": "othello", "audience": 40 }
]
}
第三个文件statement.js
function statement(invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
const format = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2
}).format;
for (const perf of invoice.performances) {
const play = plays[perf.playId];
let thisAmount = 0;
switch (play.type) {
case "tragedy":
thisAmount = 40000;
if (perf.audience > 30) {
thisAmount += 1000 * (perf.audience - 30);
}
break;
case "comedy":
thisAmount = 30000;
if (perf.audience > 20) {
thisAmount += 10000 + 500 * (perf.audience - 20);
}
thisAmount += 300 * perf.audience;
break;
default:
throw new Error(`unknown type: ${play.type}`);
}
volumeCredits += Math.max(perf.audience - 30, 0);
if (play.type === "comedy") volumeCredits += Math.floor(perf.audience / 5);
result += ` ${play.name}: ${format(thisAmount / 100)} (${perf.audience} seats)\n`;
totalAmount += thisAmount;
}
result += `Amount owed is ${format(totalAmount / 100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
}
// 导出函数
module.exports = { statement };
第4个文件kjtoday.js
const { statement } = require('./statement.js');
// 引入Node.js文件系统模块
const fs = require('fs');
const path = require('path');
// 1. 读取两个JSON文件
const readJsonFile = (filename) => {
const filePath = path.resolve(__dirname, filename);
const data = fs.readFileSync(filePath, 'utf8');
return JSON.parse(data);
};
// 定义 invoice 和 plays 数据
const invoice = readJsonFile('invoice.json');
const plays = readJsonFile('plays.json');
// 调用函数
const result = statement(invoice, plays);
console.log(result);
第五,执行办法
1、将四个文件放在同一个文件夹
2、安装好node.js 12及以上版本
3、在终端先定位打开到对应的文件夹,然后运行node kjtoday.js
就能得到和书本一样的代码和一样的运行结果
[本日志由 admin 于 2025-12-01 10:18 AM 编辑]
http://www.kjtoday.cc/trackback.asp?tbID=43
http://www.kjtoday.cc/trackback.asp?tbID=43&CP=GBK
用户登陆
站点日历
站点统计
最新评论
日志搜索
今天终于成功运行了重构2的第一个代码 [ 日期:2025-12-01 ] [ 来自: