[5, [[4, 3], 2, 1]]=>(5 - ((4 - 3) - 2 - 1))

实现一个函数,能够将诸如 [5, [[4, 3], 2, 1]] 的数组当做(5 - ((4 - 3) - 2 - 1))进行分组的减法运算,并返回结果。(不能使用eval,建议使用递归);

Notion – The all-in-one workspace for your notes, tasks, wikis, and databases. 

const ary =  [5, [[4, 3], 2, 1], [[4, 3], 2, 1]];
function subtraction(arr){
  if(!Array.isArray(arr)) return arr;
  let res = 0;
  for(let i= 0; i< arr.length; i++){
    num = subtraction(arr[i]);
    if(i == 0){
      res = num;
    }else{
      res = res - num;
    }
  }
  return res
}
console.log(subtraction(ary))
// 数组[5,[[4,3],2,1]] => 字符串(5-((4-3)-2-1)) 
let str = JSON.stringify([5,[[4,3],2,1]]).replaceAll("[", "(").replaceAll("]", ")").replaceAll(",","-");
eval(str)

猜你喜欢

转载自blog.csdn.net/SeriousLose/article/details/127767675