【问题标题】:How to change JSON String data to JSON Number data如何将 JSON 字符串数据更改为 JSON 数字数据
【发布时间】:2023-03-10 12:27:01
【问题描述】:

大家好,我正在尝试获取“review”的数值,发生的情况是在 JSON 中它将它作为字符串返回,因此我无法执行我所做的求和,导致毫无意义价值

目标是,当有人对 X 产品发表评论时,数据以 JSON 格式保存在 Firebase 中,问题是“评论”被保存为字符串而不是数字

有没有办法把这一条数据转换成数字?

这是 JSON 响应

"[{\"review\":\"4\",\"comment\":\"Good product \",\"name\":\"SnowFall\",\"image\":\"https://lh3.googleusercontent.com\",\"method\":\"google\"}]"

这是我的打字稿

callback(i, totalReviews) {

    if (!this.render) {

      this.render = true;

      let globalRating = 0;
      let globalReviews = 0;

      setTimeout(function () {

        totalReviews.forEach((review, index) => {

          globalRating += review.length;

          for (const i in review) {

            globalReviews += review[i].review;

            console.log("globalReviews", globalReviews);
          }
        })

        console.log("Raiting", globalRating);
        console.log("Reviews", globalReviews);

        let averageReviews = Math.round(globalReviews / globalRating);
        let precentage = Math.round(globalReviews * 100 / (globalRating * 5));

        $(".globalRating").html(globalRating);
        $(".percentage").html(precentage);

        let averageRating = DinamicReviews.fnc(averageReviews);

        $(".br-theme-fontawesome-stars").html(`

        <select class="ps-rating reviewsOption" data-read-only="true"></select>

        `)

        for (let i = 0; i < averageRating.length; i++) {

          $(".reviewsOption").append(`

          <option value="${averageRating[i]}">${i + 1}</option>

          `)

        }

        Rating.fnc();

      }, i * 10)
    }
  }

这就是它在 FireBase 中的保存方式FireBase RealTime Database

这是它在我的前端的外观 FrontEnd

【问题讨论】:

    标签: javascript arrays json typescript arraylist


    【解决方案1】:

    有一行您将.review 值分配给globalReviews 变量,因为这是使用+= 这将连接字符串,这就是您面临的问题。

    如果您将同一行更改为:globalReviews += +review[i].review;

    这将修复错误。

    在变量前添加+ 符号起作用的原因是因为这个符号被称为一元加号运算符,它将值转换为数字或存储值是不是它将在Unary Plus Operator documentation 之后转换的数字

    为了使这段代码安全而不添加可能的NaN,您可以使用以下语法globalReviews += +review[i].review || 0;将故障安全设置为0

    【讨论】:

    • 你太棒了,我完全解决了它,非常感谢你的文档,我会记住它以及代码的安全建议。再次非常感谢您。
    • @SnowFall np,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2013-10-26
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 2018-05-17
    • 2015-12-21
    相关资源
    最近更新 更多