gpt4 book ai didi

Javascript对象执行器

转载 作者:行者123 更新时间:2023-12-03 07:46:15 24 4
gpt4 key购买 nike

我正在尝试解决以下问题。但现在我还是做不到。谁能帮我解答一下这个问题吗?

enter image description here

我已经完成了以下代码。

<!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对象执行器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35192025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com