链接到实时代码
我目前正在为具有数千个价格点的产品提取API数据。下面,我尝试在价格中添加代码toLocaleString()
,下面的全称是<p id="price">$${product.price?.text.toLocaleString() ?? ""}</p>
。然而,它似乎没有添加逗号来使价格以千为单位读取(例如- 1,000)。
// 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价格显示与逗号,使他们正确显示为数千个数字?
数字必须是数字而不是字符串才能工作。parseFloat(numberAsString).toLocaleString()