【问题标题】:Sum values inan arrays is not working- jQuery数组中的总和值不起作用 - jQuery
【发布时间】:2021-05-20 20:02:15
【问题描述】:

我正在建立一个房产估价表。
您可以按邮政编码和类型进行过滤。
过滤后,我应该显示一个包含属性和平均价格的列表,但我不知道为什么总和不起作用。

提前感谢您的帮助:)
这是我的代码 ................................... ... ... ... ... ... ... ... ...

var houses = [{
    Postcode: "2011",
    Type: "typehouse1",
    Price: "101"
},
{
    Postcode: "2011",
    Type: "typehouse1",
    Price: "200"
},
{
    Postcode: "2010",
    Type: "typehouse1",
    Price: "234"
},
{
    Postcode: "2011",
    Type: "typehouse1",
    Price: "100"
},
{
    Postcode: "2012",
    Type: "typehouse2",
    Price: "500"
},
{
    Postcode: "2011",
    Type: "typehouse2",
    Price: "100"
},
{
    Postcode: "2013",
    Type: "typehouse2",
    Price: "100"
},
{
    Postcode: "2013",
    Type: "typehouse2",
    Price: "455"
}];
var postcodeArray = [];
var typeArray = [];

// adding unique years to yearsArray
$.each(houses, function (index) {
    var postcode = houses[index].Postcode;
    if ($.inArray(postcode, postcodeArray) == -1) {
        postcodeArray.push(postcode);
    }
});
    
//sorting by postcode
postcodeArray.sort();
var $pcode = $("#postcode");
var $housetype = $("#type");
var $container = $("#details").find("tbody");
// append the years to select
$.each(postcodeArray, function (i) {
    $pcode.append('<option value="' + postcodeArray[i] + '">' + postcodeArray[i] + '</option>');
});

$pcode.change(function () {
    var selectedpcode = this.value;
    //filter based on  selected postcode.
    typeArray = jQuery.grep(houses, function (product, i) {
        return product.Postcode == selectedpcode;
    });
    
    updateTable(typeArray);
});

$housetype.change(function () {
    var selectedtype = this.value;
    //filter select based on selected type
    selectedArray = jQuery.grep(typeArray, function (product, i) {
        return product.Type == selectedtype;
        
    });
    updateTable(selectedArray);

    var sum = 0;
      
      $(selectedArray).each(function() {
        sum += $(this)[0].Price;
        console.log("Added: ", $(this)[0].Price) 
      });
      
      console.log("Sum is:", sum);
      console.log("The average is:", sum / selectedArray.length)
});
    
    
      

//To update the table element with selected items
updateTable = function (collection) {
    $container.empty();
    for (var i = 0; i < collection.length; i++) {
        $container.append("<tr><td>" + collection[i].Postcode + "</td><td> " + collection[i].Type + "</td><td>" + collection[i].Price + "</td></tr>");
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="DrpDwn">
        Postoce<input id="postcode"></input>
        House type:<select id="type">
                <option>None</option>
                <option value="typehouse1">type house 1</option>
                <option value="typehouse2">type house 2</option>
            </select>       
</div>
<br />
Filtered houses information
    <table id="details"  border="1" cellpadding="2" cellspacing="2">
    <thead>
        <tr>
            <th>Postcode</th>
            <th>Type</th>
            <th>Price</th>
        </tr>
    </thead> 
    <tbody></tbody>   
</table>

【问题讨论】:

  • 你能提供重现问题的步骤吗?我不确定它应该如何工作。

标签: jquery arrays


【解决方案1】:

您可以尝试稍微简化一下您的代码。我已经对代码进行了一些修改,并认为您可能会发现它很有帮助。我已经在代码中详细说明了使用 cmets 的步骤:

const houses = [{
    Postcode: "2011",
    Type: "typehouse1",
    Price: "101"
  }, {
    Postcode: "2011",
    Type: "typehouse1",
    Price: "200"
  }, {
    Postcode: "2010",
    Type: "typehouse1",
    Price: "234"
  }, {
    Postcode: "2011",
    Type: "typehouse1",
    Price: "100"
  }, {
    Postcode: "2012",
    Type: "typehouse2",
    Price: "500"
  },
  {
    Postcode: "2011",
    Type: "typehouse2",
    Price: "100"
  }, {
    Postcode: "2013",
    Type: "typehouse2",
    Price: "100"
  }, {
    Postcode: "2013",
    Type: "typehouse2",
    Price: "455"
  }
];

// Get references to the elements that we'll be working with
const tbodyEl = document.querySelector('tbody');
const postcodeInputEl = document.querySelector('#postcode');
const houseTypeInputEl = document.querySelector('#type');
const averagePriceEl = document.querySelector('#average');

// Apply the event handlers to the elements that affect the results
postcodeInputEl.addEventListener('change', updateTableWithResults);
houseTypeInputEl.addEventListener('change', updateTableWithResults);

function updateTableWithResults() {
  // Clear the previous result rows and average house costs
  clearExistingResults();

  // Start by getting all the houses in the requested zip code
  let results = getHousesInZip(postcodeInputEl.value);

  // Apply house type filter 
  if (houseTypeInputEl.value !== 'None') {
    results = results.filter(house => house.Type === houseTypeInputEl.value);
  }

  // Generate the HTML and append it to the tbody
  results.map(convertHouseToTrElement)
    .forEach(trElement => {
      tbodyEl.insertAdjacentHTML('beforeend', trElement)
    });

  // Calculate the average and display it
  if (results.length > 0) {
    averagePriceEl.innerHTML = `<p>Average house price = $${getAverageHousePrice(results).toFixed(2)}</p>`;
  }
}

function clearExistingResults() {
  tbodyEl.innerHTML = '';
  averagePriceEl.innerHTML = '';
}

function getHousesInZip(zip) {
  return houses.filter(house => house.Postcode == zip);
}

function convertHouseToTrElement(house) {
  return `<tr><td>${house.Postcode}</td><td>${house.Type}</td><td>${house.Price}</td></tr>`;
}

function getAverageHousePrice(houses) {
  return (houses.reduce((sum, house) => {
    sum += parseInt(house.Price);

    return sum;
  }, 0) / houses.length);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="DrpDwn">
  Postcode<input id="postcode"> House type:
  <select id="type">
    <option>None</option>
    <option value="typehouse1">type house 1</option>
    <option value="typehouse2">type house 2</option>
  </select>
</div>
<br /> Filtered houses information
<table id="details" border="1" cellpadding="2" cellspacing="2">
  <thead>
    <tr>
      <th>Postcode</th>
      <th>Type</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
<div id="average"></div>

【讨论】:

    【解决方案2】:

    你的总和不起作用,因为 JS 正在对字符串求和,这会给你连接。

    您需要做的就是更换这部分:

    sum += $(this)[0].Price;
    

    与

    sum += parseInt($(this)[0].Price);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-22
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多