// 计算当前字符串是否是数字
    const isNumber = (val) => {
      const regPos = /^\d+(\.\d+)?$/ // 非负浮点数
      const regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/ // 负浮点数
      if (regPos.test(val) || regNeg.test(val)) {
        return true
      } else {
        return false
      }
    }
    // 用户传入的字符串
    // const str = '92-4*5/3'
    const str = '92/2-4*5'
    // const str = '4*5'
    // 将字符串分割成数组
    const arr = str.split('')
    // 准备一个容器
    let newArray = []
    // 遍历字符串数组
    arr.forEach((item, i) => {
      // 如果当前字符串是数字
      if (isNumber(item)) {
        // 拿到最后一个数组元素
        let endStr = newArray[newArray.length - 1]
        // 拿到最后一个数组元素的索引
        const endIndex = newArray.length - 1
        // 判断最后一个数组元素是否是数字
        if (isNumber(endStr)) {
          // 如果最后一个数组元素是数字,则进行拼接
          endStr += item
          // 修改最后一个数组元素
          newArray.splice(endIndex, 1, endStr)
        } else {
          // 如果最后一个数组元素是运算符,则将当前项直接添加到数组
          newArray.push(item)
        }
      } else {
        // 如果当前项是运算符,则将当前项直接添加到数组
        newArray.push(item)
      }
    })
    // 将数字与运算符遍历,将字符串类型的数字转换成数字类型
    newArray = newArray.map((item) => (isNumber(item) ? parseFloat(item) : item))

    // 通过递归算法,先判断数组元素是否只有一个,如果只有一个数组元素,则返回这个最终值,如果数组元素
    function sumResutl(arr) {
      // 如果数组元素中有乘除加减运算符
      const i1 = arr.indexOf('*')
      const i2 = arr.indexOf('/')
      const i3 = arr.indexOf('-')
      const i4 = arr.indexOf('+')
      if (i1 !== -1) {
        // 拿到乘号运算符前面数字的索引
        const index = i1 - 1
        // 计算出结果
        const result = arr[index] * arr[i1 + 1]
        // 修改数组元素
        arr.splice(index, 3, result)
        // 如果剩下的元素不只一位,则继续调用函数自身
        if (arr.length > 1) sumResutl(arr)
      } else if (i2 !== -1) {
        // 拿到乘号运算符前面数字的索引
        const index = i2 - 1
        // 计算出结果
        const result = arr[index] / arr[i2 + 1]
        // 修改数组元素
        arr.splice(index, 3, result)
        // 如果剩下的元素不只一位,则继续调用函数自身
        if (arr.length > 1) sumResutl(arr)
      } else if (i3 !== -1) {
        // 拿到乘号运算符前面数字的索引
        const index = i3 - 1
        // 计算出结果
        const result = arr[index] - arr[i3 + 1]
        // 修改数组元素
        arr.splice(index, 3, result)
        // 如果剩下的元素不只一位,则继续调用函数自身
        if (arr.length > 1) sumResutl(arr)
      } else if (i4 !== -1) {
        // 拿到乘号运算符前面数字的索引
        const index = i4 - 1
        // 计算出结果
        const result = arr[index] + arr[i4 + 1]
        // 修改数组元素
        arr.splice(index, 3, result)
        // 如果剩下的元素不只一位,则继续调用函数自身
        if (arr.length > 1) sumResutl(arr)
      }
    }

    sumResutl(newArray)
    console.log(newArray[0])
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐