JS中如何替换字符串公式中的整数以计算表达式
Solution
Step 1: Create a lookup map from order numbers to values
First, we'll convert the given array into an object that lets us quickly look up the value for any order number. This makes the replacement process efficient and straightforward.
var value_array = [ {value: "11", order: "1"}, {value: "4", order: "2"}, {value: "31", order: "3"}, {value: "41", order: "4"}, {value: "51", order: "5"}, {value: "61", order: "6"}, {value: "71", order: "7"}, {value: "80", order: "8"}, {value: "91", order: "9"}, {value: "101", order: "10"}, {value: "111", order: "11"}, {value: "128", order: "12"}, {value: "131", order: "13"}, {value: "145", order: "14"} ]; // Build the lookup map const orderMap = value_array.reduce((map, item) => { const order = parseInt(item.order, 10); const value = parseInt(item.value, 10); map[order] = value; return map; }, {});
Step 2: Replace integers in the formula with corresponding values
Use a regular expression to find all integers in the formula string, then replace each match with the corresponding value from our lookup map.
const originalFormula = "((1+14)*5+12*3-7*8/2+4)"; // Replace each integer with the mapped value const replacedFormula = originalFormula.replace(/\d+/g, match => { const order = parseInt(match, 10); // Keep the original integer if no matching order exists (adjust to throw error if needed) return orderMap[order] ?? match; }); console.log(replacedFormula); // Output: ((11+145)*51+128*31-71*80/4+41)
Step 3: Evaluate the modified formula to get the result
Since we have a valid arithmetic expression, we can use eval() to compute the final result. Note: Only use eval() here because we control both the original formula and replacement values—avoid it with untrusted input.
const result = eval(replacedFormula); console.log(result); // Output: 10545
Additional Notes
- If your formula might include integers without a matching entry in
value_array, the?? matchclause preserves the original number instead of breaking the expression. You can replace this with an error throw if you want to enforce full coverage of order numbers. - Parsing both
orderandvalueto integers ensures we handle numeric operations correctly, even though the original array stores these values as strings.
内容的提问来源于stack exchange,提问作者alperzzz
相关产品推荐
相关产品推荐

