从表中逐个获得最高价值

时间:2016-04-05 10:20:41

标签: javascript jquery

如何逐类获取表中的最高值?我尝试过以下方法:

HTML

<table>
    <tr><td class="speed">1.1</td></tr>
    <tr><td class="speed">3.1</td></tr>
    <tr><td class="speed">5.5</td></tr>
    <tr><td class="speed">2.0</td></tr>
</table>

jQuery的/使用Javascript

function gethighestspeeds(){

    var speeds = $(".speed").map(function() {
       return parseFloat(this.text, 10);
    }).get();

    var highestspeed = Math.max.apply(Math, speeds);
    alert(highestspeed)
}   

另外,如果&gt;我如何获得所有值?超过一定数量?

3 个答案:

答案 0 :(得分:0)

试试这个........

var certainNumber=2.2; //Whatever you want to set

function gethighestspeeds(){

   var speeds = $(".speed").map(function() {
       return parseFloat(this.text, 10) > parseFloat(certainNumber);
       }).get();


}   

答案 1 :(得分:0)

您必须在$(this).text()函数中使用this.text代替map

return parseFloat($(this).text(), 10);

答案 2 :(得分:0)

this.text未定义td元素,您需要解析parseFloat($(this).text(), 10);

function gethighestspeeds() {

  var speeds = $(".speed").map(function() {
    return parseFloat($(this).text(), 10);
  }).get();

  var highestspeed = Math.max.apply(Math, speeds);
  snippet.log('high: ' + highestspeed);

  var num = 2.3;
  var array = $(".speed").map(function() {
    var flt = parseFloat($(this).text(), 10);
    return flt > num ? flt : undefined;
  }).get();
  snippet.log('array: ' + array)

  //if you already have the speeds array
  var array2 = speeds.filter(function(val) {
    return num < val;
  });
  snippet.log('array2: ' + array)
}
gethighestspeeds();
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="speed">1.1</td>
  </tr>
  <tr>
    <td class="speed">3.1</td>
  </tr>
  <tr>
    <td class="speed">5.5</td>
  </tr>
  <tr>
    <td class="speed">2.0</td>
  </tr>
</table>