javascript - 使用 fs.writeFile(),出现一个没有方括号或引号的数组?
问题描述
出于某种原因,当使用 fs.writeFile() 时,数组的工作方式与 console.log() 不同。为什么引号和方括号不见了?
word = args[0].split("")
//args is an array of the arguments the user writes in the discord command
//let's pretend that the word is: "test"
fs.writeFile('word.json', `{"word": ${word}}`, (err) => {
if (err) {
throw err
}
console.log(`The word: "${args[0]}" has been saved`)
})
//writes {"word": t, e, s, t} giving a billion errors
console.log(word)
//outputs [ 't', 'e', 's', 't' ]
解决方案
看来word
是['t', 'e', 's', 't']
。
所以,当你这样做时:
`{"word": ${word}}`
该${word}
语法试图将上述数组转换为字符串,以便调用.toString()
该数组并为您提供:
t, e, s, t
所以,你的最终结果是:
{"money": t, e, s, t}
这完全符合预期。
你没有在这里展示你真正想要做什么,但这个问题的根源似乎又回到了这里:
word = args[0].split("")
您在哪里获取args
数组的第一个元素并将其拆分为一个字符数组,并且该字符数组本身不是字符串,并且似乎是您的问题的原因。
作为演示,您可以看到:
console.log(['t', 'e', 's', 't'].toString())
会给你:
t, e, s, t
而在这:
console.log(['t', 'e', 's', 't']);
查看console.log()
您传递给它的参数的类型,并使用特定于类型的逻辑来显示它。它不只是盲目地调用.toString()
它。相反,它将其显示为数组。
因此,最终${word}
语法具有不同的显示规则console.log(word)
。请注意,这fs.writeFile()
与您如何准备传递给fs.writeFile()
.
推荐阅读
- html - 阅读较少后更改按钮/按钮上的文本
- reactjs - 未找到模块:无法解析“swiper/react”
- sql - 在 SQL Server 中使用平均法计算 COGS
- typescript - Jasmine 中的单元测试在不同的显示比例下失败
- python - 就 POC 项目寻求建议/建议,通过监控网络/arp 变化来检测气隙漏洞
- mysql - 每小时运行 cron 更新 100 万条记录失败
- java - File.listFiles() 在 Linux 中失败
- feign - UNCAUGHT_EXCEPTION:未捕获的异常出现在控制器建议中
- apache-kafka - 有没有办法找出正在发布到主题的特定 Kafka msg 的分区索引/Id/编号?
- exchange-server - 是一种订阅 EWS 通知的方式,如 Microsoft Graph API 以获取通知