分配字符串的变量值

时间:2018-07-10 00:44:56

标签: javascript variable-assignment

我是Java语言的新手-我尝试在网络上搜索无法将这种情况纳入上下文。

这是情况:

import * as People from ./People.json
import * as Education from ./Education.json
import * as Vehicle from ./Vehicle.json
...
function transpose(str : string) {
  let data = {};
  if(validate(str))  //validate function returns true if valid string
    data = str  //data takes in the string value and uses variable name
    runFile(data); //runFile expects data to be a JSON type
  ...
}

如果假设str = {"People",那么数据将等于变量People,或者如果str = {"Vehicle"数据将是str,则基本上如何将str(字符串变量转换为变量) Vehicle变量。

我知道可以使用{“ People”:People,“ Vehicle”:Vehicle}的地图来完成此操作,似乎应该有更好的方法吗?我也研究了eval(str),但似乎并不能解决问题。

任何帮助将不胜感激。

谢谢

2 个答案:

答案 0 :(得分:3)

“地图”确实是最好的方法。好消息是您可以保存一些带有速记属性名称的按键(ES2015):

import * as People from ./People.json
import * as Education from ./Education.json
import * as Vehicle from ./Vehicle.json

const lookup = {People,Education,Vehicle}; // equivalent to {"People":People, ...}

function transpose(str : string) {
  let data = {};
  if(validate(str))  //validate function returns true if valid string
    data = lookup[str]  //data takes in the string value and uses variable name
    runFile(data); //runFile expects data to be a JSON type
  ...
}

答案 1 :(得分:-1)

如果要将JSON作为参数传递给转置函数很有用。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="blog">
  <div class="content">
    <img src="https://i.imgur.com/fUty9h8.jpg" />
    <img src="https://i.imgur.com/fUty9h8.jpg" />
    <img src="https://i.imgur.com/fUty9h8.jpg" />
  </div>
</div>