Javascript对象执行器

Javascript对象执行器

我正在尝试解决以下问题。但是现在我还是不能。谁能帮我解决问题?

javascript - Javascript对象执行器-LMLPHP

我已经完成了以下代码。

<!DOCTYPE html>
<html>
    <head>
        <title>Javascript Test Solution</title>
   </head>
<body>

    <h1>Solution 2</h1>

    <p id="demo"> </p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var executor = {
    "string": function (value) { return "" + value; },
    "number": function (value) { return 1 + parseInt(value, 10); },
    run     : function (data) {

    // split the string and remove whitespaces
    var str_array = data.split(/\s*,\s*/);

    for(var i = 0; i < str_array.length; i++) {

        console.log(str_array[i]);

        if (typeof str_array[i] === "function") {
            console.log('function');
        }

    }
        returnData = executor.string(data);
        return returnData;
    }
};
var input = "foo,,bar,2,string(hi),string(5)";
document.getElementById("demo").innerHTML = executor.run(input);
</script>
</body>




感谢您的宝贵时间。

最佳答案

正如评论中已经解释的那样,最初的问题是检查功能。由于该值将具有(),因此您需要从字符串中提取函数名称,然后检查其是否存在。



var executor = {
  "string": function(value) {
    return "" + value;
  },
  "number": function(value) {
    return 1 + parseInt(value, 10);
  },
  rootOf: function(value) {
    return Math.sqrt(value);
  },
  run: function(data) {

    // split the string and remove whitespaces
    var str_array = data.split(/\s*,\s*/);

    var result = str_array.map(function(value) {
      var fnparts = value.match(/(.*)\((.*)\)/)
      if (fnparts && fnparts.length == 3) { //if function
        try {
          if (typeof executor[fnparts[1]] == 'function') { //check whether the function exists in the executor
            if (fnparts[2].trim()) { //if there are parameters then pass them to the function
              return executor[fnparts[1]].apply(window, fnparts[2].split(/\s*,\s*/))
            } else { //else just call the function
              return executor[fnparts[1]]();
            }
          } else {
            return 'error';
          }
        } catch (e) {
          return 'error';
        }
      } else { //if it is not a function then call the string/number function
        if (/^\d+$/.test(value)) {
          return executor.number(value);
        } else {
          return executor.string(value);
        }
        return value;
      }
    });

    return result;
  }
};
document.getElementById("demo1").innerHTML = executor.run("foo,,bar,2,string(hi),string(5)");
document.getElementById("demo2").innerHTML = executor.run("adf, rootOf(9)");
document.getElementById("demo3").innerHTML = executor.run("foo,,bar,2,string(hi),string(5)");
document.getElementById("demo4").innerHTML = executor.run("foo,,bar,2,string(hi),string(5)");

<h1>Solution 2</h1>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>

关于javascript - Javascript对象执行器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35192025/

10-12 05:30