我试图解决以下问题。但现在我仍然无法做到。有人可以帮我解决这个问题吗?
我已完成以下代码。
<!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>
感谢您宝贵的时间。
答案 0 :(得分:1)
正如评论中已经解释的那样,最初的问题是检查功能。由于该值将为<div class="Main animated fadeIn">
<!--To make the Site Unique, I have included Several Trailers for the Main Landing Page !-->
<video autoplay="" id="bgvid" loop="" poster="polina.jpg"><source src=
"img/indexMV.mp4" type="video/mp4"> <source src="img/indexMV.mp4"
type="video/mp4"></video>
</div>
,因此您需要从字符串中提取函数名称,然后检查它是否存在。
()
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)");