首页 > 解决方案 > 使用 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' ]

标签: javascriptnode.jsdiscorddiscord.js

解决方案


看来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().


推荐阅读