javascript从循环输出计算平均值
我想去掉“未定义”并平均输出到控制台的priceList数组值。我使用网页在Chrome控制台中应用此代码。谢谢你的帮助javascript从循环输出计算平均值,javascript,arrays,average,Javascript,Arrays,Average,我想去掉“未定义”并平均输出到控制台的priceList数组值。我使用网页在Chrome控制台中应用此代码。谢谢你的帮助 //selects the all of the designer cards var experts = document.querySelectorAll('.expert-card__content'); //This tells us how many designer cards there are var expertsQty = experts.length;
//selects the all of the designer cards
var experts = document.querySelectorAll('.expert-card__content');
//This tells us how many designer cards there are
var expertsQty = experts.length;
var expertContent =document.getElementsByClassName("expert-list-summary txt--minor");
//expertContent[0].innerText
var i;
var priceMedian;
var prices;
var priceList = 0;
for(i=0; i<experts.length; i++){
//Grabs the content
var str = expertContent[i].innerText;
//This determines the position of the last $ in the text
var strPosition = expertContent[i].innerText.lastIndexOf("$");
//This goes to the position of the $ and shows the 1 word after it.
var expertPrice= str.substring(strPosition + 1);
//iterate through expert content
parseInt(expertPrice);
parseInt(prices);
priceList = prices += expertPrice;
}
//选择所有设计器卡
var experts=document.queryselectoral(“.expert-card__内容”);
//这告诉我们有多少设计师卡
var expertsQty=专家长度;
var expertContent=document.getElementsByClassName(“专家列表摘要txt--minor”);
//expertContent[0]。innerText
var i;
var中值;
var价格;
var-priceList=0;
对于(i=0;i我查看了您提供的链接中的网站。以下是计算平均值的方法:
// get the second <p>s of inside the <div>s with the classes expert-list-summary and txt--minor
var experts = document.querySelectorAll(".expert-list-summary.txt--minor p:nth-child(2)");
var qty = experts.length; // the quantity is the cound of those p elements
var prices = 0; // prices must be initialized to 0 (otherwise you get an average of NaN)
for(var i = 0; i < experts.length; i++) {
var str = experts[i].textContent; // get the text content of that p element
str = str.replace(/,/g, ''); // remove commas as they're not valid in numbers
var price = parseInt(str.match(/\$(\d+)/)[1]); // use a rgular expression to retrieve the number it's clearer (match any number after the dollar sign, read more about regular expressions)
prices += price; // add this price to the prices (accumulate the prices)
}
var average = prices / qty; // the average is the sum of prices divided by the quantity
//使用class expert list summary和txt--minor获取s中的第二个s
var experts=document.queryselectoral(“.expert-list-summary.txt--第n个子项(2)”;
var qty=experts.length;//数量是这些p元素的坐标
var prices=0;//价格必须初始化为0(否则得到的平均值为NaN)
对于(变量i=0;i
你的问题有点模糊。你到底想知道什么?parseInt
获取一个字符串并返回一个数字!应该这样使用:var number=parseInt(“45”);
!另外,网站上的数字是这种格式的3456
,这不是一个有效的数字!