我可以从对象创建if语句吗?

时间:2019-01-07 17:33:46

标签: javascript arrays

我有一个Google Chrome扩展程序,该扩展程序允许用户使用扩展程序options.html页面中的表单将参数保存到chrome.storage区域。他们输入的参数将合并到一个对象中,该对象将保存到chrome.storage.local。

当他们访问网站时,我从内容脚本的存储中加载了该对象。然后,我需要根据用户提供的数据创建if语句。

给出这样的变量(由我设置或从其他来源(而不是用户)获取的值)。其他示例包括用户所在页面的document.referrer或页面上.href标签的<a>属性。

var variable = "foo"; // this variable and its value of 'foo' here is created by me

这个对象(由用户提供):

const ifStatement = {
  "operator": "and", // &&, logical operator selected by user
  "conditions": [
    [
      "variable", // a variable name saved to storage as a string. the user chose it from a list of provided variables
      "===",      // comparison operator saved as a string, selected by user
      "foo"       // custom string entered by user, intended by them to match against the variable they identified
    ],
    [
      "variable",
      "!==",
      "bar"
    ]
  ]
}

如何创建如下所示的if语句?

if ( variable === "foo" && variable !== "bar" ) {
  // do something
}

这是用户用来向我提供ifStatement对象中的值的UI的屏幕截图。也许这将有助于可视化我在做什么。

enter image description here

2 个答案:

答案 0 :(得分:0)

您将需要一个解释用户提供的对象的函数。对于您提供的变量,我建议将它们定义为单个对象的属性。所以代替:

var path = "foo"

...您将拥有:

var vars = { path: "foo" }

该函数将使用vars和用户提供的对象。它将返回falsetrue。有了这样的结果,您可以轻松地编写if语句。真正的核心问题是产生布尔值。

这是怎么做:

function evalBoolean(vars, {operator, conditions}) {
    return conditions[operator === "and" ? "every" : "some"](([name, cmp, value]) => ({
            "===": (a, b) => a === b,
            "!==": (a, b) => a !== b,
            "<"  : (a, b) => a < b,
            ">"  : (a, b) => a < b,
            "<=" : (a, b) => a <= b,
            ">=" : (a, b) => a >= b,
        })[cmp](vars[name], value)
    );
}

// Demo
var vars = { path: "foo" };

const expression = {
  "operator": "and",
  "conditions": [
    [
      "path",
      "===",
      "foo"
    ],
    [
      "path",
      "!==",
      "bar"
    ]
  ]
}

console.log(evalBoolean(vars, expression));

答案 1 :(得分:-1)

在阅读下面的示例之前,让我指出,从安全角度来看,从字符串任意执行代码是危险的。话虽这么说,这样的事情应该起作用。随时询问您是否需要帮助以了解幕后情况。

让我们说对象存储为var obj。

const obj = {
  "operator": "and",
  "conditions": [
    [
      "path",
      "===",
      "foo"
    ],
    [
      "path",
      "!==",
      "bar"
    ]
  ]
};

const conditionCount = obj.conditions.length;
let statement;

for (var i = 0; i < conditionCount; i++) {
  statement += obj .conditions[i];
  if (i < objectConditionCount - 1) {
    statement += ` ${obj.operator} `;
  }
}

if (exec(statement)) {
//function you want to execute
}

相关问题