Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

nodejs 字符串拼对象出现[object object] ,如何才能正常解析?

const MAIN_TEMPLATE = `
    import Vue from 'vue'
    import VueRouter from 'vue-router'
    import Home from '../views/Home.vue'
    Vue.use(VueRouter)
    const routes = [{
     path: '/', name: 'Home', component: Home,children:${router}
     },]
    const router = new VueRouter({
     mode: 'history', base: process.env.BASE_URL, routes})
    export default router
`
fs.writeFile(path,MAIN_TEMPLATE,err=>{})

上面代码执行后是下面带有 [object object]
image.png
children的数据是处理过的!想拼接后写入跟下面截图一样
router 是一个数组对象,
image.png

试过JSON.parse,JSON.stringify等 都是不行
请问有什么办法嘛~


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

字符串拼接符的原理是String的concat的api。

  • 比如
let b = [{name:'b'}]
let a =  `name${b}`;
  • node本身不支持es6,经babel会编译为es5代码
var b = [{
  name: 'b'
}];
var a = "name".concat(b);
  • 当字符串与数组进行拼接时,会展示为[object object]形式。
  • 所以如果要想不展示为[object object] 应当将数组变量转为字符串
var b = `[{
  name: 'b'
}]`;
var a = "name".concat(b);
  • 此时结果为
name[{
    name: 'b'
}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...