首页 > 解决方案 > 如何使用 JavaScript 将逗号添加到来自 API 的数千个数字

问题描述

链接到实时代码。

我目前正在提取价格为数千的产品的 API 数据。下面,我尝试将代码添加toLocaleString()到价格中,下面是<p id="price">$${product.price?.text.toLocaleString() ?? ""}</p>. 但是,它似乎没有添加逗号以使价格以千为单位读取(例如 - 1,000)。

JS代码

// Fetch Data
async function getData() {
  const res = await fetch(url);
  const data = await res.json();
  let output = "";
  // Loop through first 'groups' array
  data.groups.map(function (group) {
    // Loop through each 'equipments' array
    group.equipments.map((product) => {
      // Define below variable to match cat products only
      const catProducts =
        product["dealer-name"] === "DEALER NAME";
      // If the dealer name is everything but cat products (aka only bfe products)..
      if (!catProducts) {
        // Loop through each 'photos' array
        product.photos.map(() => {
          // Then output the data
          // If year is undefined, replace with empty string
          output += `
            <div class="card">
            <img class="img-fluid" src=${product.photos[0].text} alt=${
            product.model
          } />
            <div class="card--body">
              <h3>${product.year ?? ""} ${product.manufacturer} ${
            product.model ?? ""
          }</h3>
              <p>${product.city ?? "City Not Available"}, ${product.state}</p>
              <p>${product.hours} hours</p>
              <p id="price">$${product.price?.text.toLocaleString() ?? ""}</p> <--- Not working
              <a href='https://used.battlefieldequipment.ca/en/${
                product["group-code"]
              }/${
            product["serial-number"]
          }' class="btn btn-primary">View Details</a>
              </div>
            </div>         
        `;
        });
      }
    });
  });
  // Add to slider
  $(".used-slider").slick("slickAdd", output);
}

getData();

知道如何让 API 价格以逗号显示,使它们正确显示为数千个数字吗?

标签: javascript

解决方案


该数字必须是数字而不是字符串才能起作用。parseFloat(numberAsString).toLocaleString()


推荐阅读