如何在JavaScript中读取JSON文件实现随机建议选取功能
随机匹配建议编号与JSON内容的解决方案
核心逻辑很简单:JSON是数组结构,只需读取数组后,利用数组索引(注意数组从0开始,生成的编号需减1)就能获取对应建议,无需特殊内置函数。以下分两种常见场景给出实现代码:
场景1:浏览器前端环境
方法A:直接嵌入JSON数组
把JSON内容直接定义为JS变量,适合建议数量不多的情况:
// 你的建议数组(可直接从JSON文件复制过来) const adviceList = [ "When in the backrooms, keep your eyes low, for the walls have ears and the floors have eyes.", "Beware the flickering lights, for they are whispers of entities unseen.", "Navigate the endless halls with caution, for each turn may lead to another layer of despair.", // 更多建议内容... ]; function Advice_picker() { // 生成0到数组长度-1的随机索引(自动适配建议数量) const randomIndex = Math.floor(Math.random() * adviceList.length); const randomAdvice = adviceList[randomIndex]; // 输出编号(索引+1对应1-50的编号规则)和建议 console.log(`建议编号:${randomIndex + 1}`); console.log(randomAdvice); return randomAdvice; } // 调用函数获取随机建议 Advice_picker();
方法B:通过Fetch读取本地JSON文件
适合建议内容单独存放在JSON文件的场景,注意本地运行需用服务器(如Live Server),否则会触发跨域限制:
async function Advice_picker() { try { // 读取本地JSON文件 const response = await fetch('./advice.json'); const adviceList = await response.json(); // 生成随机索引并获取建议 const randomIndex = Math.floor(Math.random() * adviceList.length); const randomAdvice = adviceList[randomIndex]; console.log(`建议编号:${randomIndex + 1}`); console.log(randomAdvice); return randomAdvice; } catch (error) { console.error('读取建议文件失败:', error); } } // 调用异步函数 Advice_picker();
场景2:Node.js后端环境
使用Node.js的fs模块读取JSON文件:
const fs = require('fs').promises; async function Advice_picker() { try { // 读取并解析JSON文件 const fileContent = await fs.readFile('./advice.json', 'utf8'); const adviceList = JSON.parse(fileContent); // 生成随机索引 const randomIndex = Math.floor(Math.random() * adviceList.length); const randomAdvice = adviceList[randomIndex]; console.log(`建议编号:${randomIndex + 1}`); console.log(randomAdvice); return randomAdvice; } catch (error) { console.error('读取建议文件失败:', error); } } // 执行函数 Advice_picker();
关键注意点
- 数组索引从0开始,所以你之前生成的1-50编号,需要转成
编号-1才能对应数组的正确位置; - 用
adviceList.length代替硬写的50,代码会自动适配JSON里的建议数量,不用手动修改数字; - 读取文件的操作都是异步的,需要用
async/await处理Promise。
内容的提问来源于stack exchange,提问作者Roborou
相关产品推荐
相关产品推荐

