我从数组A和B中获取随机值并尝试比较它们的求解值,因为数组中的值是字符串,如何让它们编号并解决它们是不行的?
.controller('questions', function($scope) {
var A = ['6-2', '7+3', '8*1', '9/3', '8+1'];
var B = ['1+5', '7-3', '10-5', '10/2', '3*2'];
var questionA = A[Math.floor(Math.random() * A.length)];
var questionB = B[Math.floor(Math.random() * B.length)];
if (questionA > questionB) {
console.log('It\'s bigger ');
} else {
console.log('It\'s smaller');
}
});
答案 0 :(得分:3)
您可以使用$scope.$eval()
获取等式的结果:
var answerA = $scope.$eval(questionA),
answerB = $scope.$eval(questionB);
if(answerA > answerB)
答案 1 :(得分:0)
eval
的替代
var A = ['6-2', '7+3', '8*1', '9/3', '8+1'];
var B = ['1+5', '7-3', '10-5', '10/2', '3*2'];
var len = Math.max(A.length, B.length);
for (var i = 0; i < len; i++) {
var r1 = evaluate(A[i]);
var r2 = evaluate(B[i]);
var msg = "It's " + (+r1 > +r2 ? "Bigger" : "Smaller");
console.log(msg, r1, r2);
}
function evaluate(str) {
var opReg = /[-+\/\*]/g;
var op_arr = str.match(opReg);
var result = 0;
var sortOrder = {
"*": 1,
"/": 2,
"+": 3,
"-": 4
}
op_arr.sort(function(a, b) {
var s1 = sortOrder[a];
var s2 = sortOrder[b];
return s1 > s2 ? 1 : s1 < s2 ? -1 : 0;
}).forEach(function(op) {
var val_arr = getValueArr(str, op)
result = calculate(val_arr, op);
str = str.replace(val_arr[0] + op + val_arr[1], result)
});
return result;
}
function getValueArr(str, op) {
var r = str.split(op);
var v1 = 0;
var v2 = 0;
var opReg = /[-+\/\*]/g;
v1 = opReg.test(r[0]) ? r[0].split(opReg).reverse()[0] : r[0];
v2 = opReg.test(r[1]) ? r[1].split(opReg)[0] : r[1];
return [v1, v2];
}
function calculate(val, op) {
switch (op) {
case "-":
return +val[0] - +val[1];
case "+":
return +val[0] + +val[1];
case "*":
return +val[0] * +val[1];
case "/":
return +val[0] / +val[1];
}
return 0;
}
evaluate('6-2+4*2')
&#13;