【问题标题】:Node JS How to Convert String into ObjectNode JS 如何将字符串转换为对象
【发布时间】:2014-08-20 07:27:44
【问题描述】:

示例代码为:

// 4. execute tower.init latter read from bellow (1)
tower={
  init:function(){ console.log('horee im here now, finaly after a day code');}
}

// 3. app object
app ={ 
  publish:function(what,data){
     data.nextModule.init();
  }
}
// 2. then call this funct
var fires = function(){
   return app.publish('subscriber',{ nextModule : 'tower'});
}
// 1. execute this first
fires();

解释问题

  • 当我开火fires() 1.
  • 2.isfineapp.publish('text',{nextModule:'tower');
  • 绕过到 3.app.publish(text,data)

我的问题是

我想将data.nextmodule --> 转换为对象或函数 然后调用塔模块.init()

data.nextModule.init() 无法执行,因为nextModuleString

如何让这段代码像这样运行

data.'tower'.init();

我已阅读此参考资料

豪沙尔特的回答 converting an object to a string !不是将字符串转换为对象

node js 可以吗?
我们可以像JSON.stringify(data) 一样转为反对吗?

终端更新错误

         throw err;
            ^
 TypeError: Object tower has no method `init`

【问题讨论】:

  • 您在寻找括号符号吗?见这里developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • Node.js 使用 Chrome 的 V8 javascript 引擎,该引擎实现了 ECMA-262 中指定的 ECMAScript。所以是的,如果你可以在浏览器中完成,你可以在 Node 中完成。
  • 抛出错误data["nextModule"].init();typeError: Object tower has no method init..

标签: javascript node.js object


【解决方案1】:

两件事,首先将标识符 new 更改为其他内容。

第二,

data.newxtModule 是一个字符串,表示脚本中的变量。所有变量都是GLOBAL 对象的一部分。因此,您可以通过将该变量的名称以字符串格式传递给 GLOBAL 对象来检索该变量。并且您将可以拨打塔的init()

只需改变这一行,

data.nextModule.init();

到,

GLOBAL[data.nextModule].init();

最终代码应如下所示。

// 4. execute tower.init latter read from bellow (1)
tower={
  init:function(){ console.log('horee im here now, finaly after a day code');}
}

// 3. app object
app ={ 
  publish:function(what,data){
     GLOBAL[data.nextModule].init();
  }
}
// 2. then call this funct
var new1 = function(){
   return app.publish('subscriber',{ nextModule : 'tower'});
}
// 1. execute this first
new1();

这里是Fiddle

【讨论】:

  • 当然我的真实代码不是new 它的fire() 我将编辑但它仍然抛出错误没有方法初始化.. js 可以做到这一点为什么节点不能..??
  • 我在浏览器上用 js 试试它的工作原理.. 但它在 nodejs 上仍然有错误什么是 GLOBAL[]?它是一种变量还是数组?我们可以像转换JSON.stringify(data) 一样转换字符串吗?谢谢..
  • 你可以把Node中的GLOBAL想象成浏览器中的窗口。它包含所有全局声明的变量!是否可以对 GLOBAL 对象进行字符串化取决于对象内是否存在循环链接。如果您的 GLOBAL 对象包含循环(一个属性引用其他属性等),则 JSON.stringify 将引发错误。 GLOBAL 最有可能具有循环属性。
  • 另外,您的data 是一个对象stringify,它会阻止data.nextModule 工作。如果您stringifydata 参数,它将返回您的字符串,您将无法在字符串上调用 nextModule :)
【解决方案2】:

将“塔”改为塔。

顺便说一句,你最好不要使用“新”这个关键词。

【讨论】:

  • 我编辑并尝试fires() 它的静止对象没有方法.. 通过tryig convert(data) 修复到数据对象中怎么样
  • 但如果您更新不带引号的字符串 'tower' 效果会很好。这是Fiddle
猜你喜欢
  • 2022-06-13
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2021-02-03
  • 2018-07-19
相关资源
最近更新 更多