最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

将结果存储为外部对象的一部分时将eval转换为函数吗?

IT培训 admin 6浏览 0评论

将结果存储为外部对象的一部分时将eval转换为函数吗?

我正在尝试将一些使用eval的代码转换为基于these examples的Function,并且我不太了解如何将函数调用的结果存储为现有对象的一部分。我在这里想念什么?

async function test(){
  let obj={"Name":"BOB"}
  let ret={};

  //eval- works perfectly. stores the result in ret.eval
  let evalstr='ret.eval=obj["Name"].toLowerCase()'
  eval(evalstr)

  //function- 1st attempt- ret not defined
  let funcstr='ret.function=obj["Name"].toLowerCase()'
  Function('"use strict";return (' + funcstr + ')')();

  //2nd attempt-obj not defined
  let funcstr='obj["Name"].toLowerCase()'
  ret.function=Function('"use strict";return (' + funcstr + ')')();

  console.log(ret)
}

test()
回答如下:

我不确定您为什么要尝试这样做,根据提供的示例,我不推荐这样做。我坚信,如果您可以提供更多背景信息,那么还有更好的方法可以达到预期的结果。

也就是说,如果要修复代码,则需要使ret和/或obj可用于新创建的Function,这涉及将它们声明为参数,然后传递参数。

async function test(){
  let obj={"Name":"BOB"}
  let ret={};

  //eval- works perfectly. stores the result in ret.eval
  let evalstr='ret.eval=obj["Name"].toLowerCase()'
  eval(evalstr)

  //function- 1st attempt- ret not defined
  let funcstr='ret.function=obj["Name"].toLowerCase()'
  Function('ret', 'obj', '"use strict";return (' + funcstr + ')')(ret, obj);

  //2nd attempt-obj not defined
  funcstr='obj["Name"].toLowerCase()'
  ret.obj=Function('obj', '"use strict";return (' + funcstr + ')')(obj);

  console.log(ret)
}

test()

将结果存储为外部对象的一部分时将eval转换为函数吗?

我正在尝试将一些使用eval的代码转换为基于these examples的Function,并且我不太了解如何将函数调用的结果存储为现有对象的一部分。我在这里想念什么?

async function test(){
  let obj={"Name":"BOB"}
  let ret={};

  //eval- works perfectly. stores the result in ret.eval
  let evalstr='ret.eval=obj["Name"].toLowerCase()'
  eval(evalstr)

  //function- 1st attempt- ret not defined
  let funcstr='ret.function=obj["Name"].toLowerCase()'
  Function('"use strict";return (' + funcstr + ')')();

  //2nd attempt-obj not defined
  let funcstr='obj["Name"].toLowerCase()'
  ret.function=Function('"use strict";return (' + funcstr + ')')();

  console.log(ret)
}

test()
回答如下:

我不确定您为什么要尝试这样做,根据提供的示例,我不推荐这样做。我坚信,如果您可以提供更多背景信息,那么还有更好的方法可以达到预期的结果。

也就是说,如果要修复代码,则需要使ret和/或obj可用于新创建的Function,这涉及将它们声明为参数,然后传递参数。

async function test(){
  let obj={"Name":"BOB"}
  let ret={};

  //eval- works perfectly. stores the result in ret.eval
  let evalstr='ret.eval=obj["Name"].toLowerCase()'
  eval(evalstr)

  //function- 1st attempt- ret not defined
  let funcstr='ret.function=obj["Name"].toLowerCase()'
  Function('ret', 'obj', '"use strict";return (' + funcstr + ')')(ret, obj);

  //2nd attempt-obj not defined
  funcstr='obj["Name"].toLowerCase()'
  ret.obj=Function('obj', '"use strict";return (' + funcstr + ')')(obj);

  console.log(ret)
}

test()
发布评论

评论列表 (0)

  1. 暂无评论