用于将字符串转换为对象的 eval 替代方法

Alternative to eval for converting a string to an object

我有一个函数使用 eval 将带有表达式的字符串转换为基于参数的对象。

let indexType = ["Mac", "User", "Line", "Mask", "Ip", "Location"]

const filterIndex = (item) => {
  filteredIndexSearch = []
  eval(`search${item}`).forEach((e) => filteredIndexSearch.push(searchData[e.key]))
}

filterIndex(indexType[searchTotal.indexOf(Math.max(...searchTotal))])

searchData 是一个数组,returns 值基于用户输入。

searchTotal 是一个数组,其中包含每个搜索{item} 数组的长度。

filterIndex函数从searchData数组中取最大值对应indexType数组,然后通过eval将字符串转为对象传递给filteredIndexSearch数组

什么是 eval 的更好替代品?

编辑

要添加有关此功能的更多信息:

searchData = [
  [
    {
      key: 1,
      data: "0123456789101"
    },
    {
      key: 1,
      data: "John Smith"
    }
  ],
  [
    {
      key: 2,
      data: "0123456789102"
    },
    {
      key: 2,
      data: "Jane Smith"
    },
  ]
]

const search = (data, key, container) => {
  if (!data) data = "";
  if (data.toLowerCase().includes(string)) {
    container = container[container.length] = {
      key: key,
      data: data
    }
  }
}

const returnSearch = () => {
  for (let i = 0; i < searchData.length; i++) {
    search(searchData[i][0].data, searchData[i][0].key, searchMac)
    search(searchData[i][1].data, searchData[i][1].key, searchUser)
  }
}

returnSearch()

数据不完整,但希望传达我正在尝试做的事情。

search 将获取用户输入,并将信息存储在相应的数组中。如果我输入“Jo”,它将 return searchUser 数组仅包含“John Smith”值,而所有其他值都具有相同的键。输入“102”returns searchMac 的值是“0123456789102”,所有其他值都具有相同的键。

一天结束的时候。我只想在不使用 eval.

的情况下将 search${parameter} 转换为对象

任何时候遇到名为 x0、x1 等变量的情况,这应该是一个危险信号,告诉您应该改用数组。变量名永远不应该在语义上有意义——也就是说,代码应该 永远不会 依赖变量名来确定代码的行为方式。将 search0 等转换为 search 项的数组。然后使用:

 const filterIndex = (item) => search[item].map(i => searchData[i.key]);
 filteredIndexSearch = filterIndex(indexType[searchTotal.indexOf(Math.max(...searchTotal))]);

(简化您的代码)。请注意,在您的代码中, filteredIndexSearch 在箭头函数内部进行了修改。最好有它 return 如上的结果。

将您的全局数组移动到一个对象中。

您似乎在某个地方定义了数组,例如:

searchMac = [...];
searchUser = [...];
...

我没有将它们定义为单独的数组,而是将它们定义为对象中的属性:

searchIndices.Mac = [...];
searchIndices.User = [...];
...

然后,您可以将 eval().forEach 替换为 searchIndices[item].forEach,而不是使用 eval

如果您的搜索顺序不重要,您可以循环遍历 searchIndices:

的键
Object.keys(searchIndices).forEach(item => {
  searchIndices[item].forEach(...);
});

这确保如果您在 searchIndices 中添加或删除条目,您将不会错过它或在未定义的搜索索引上意外出错。