How can I display the outcome of the for loop in h

2019-07-22 04:35发布

I'm new in this (JS, Rails and highcharts but they are really nice) and I would really appreciate some help. My story is that I have a for loop and I want to display the outcome of the for loop in highcharts. How should I do this?

<p>A n: <%= @calculation.a_n %></p>
<p>H: <%= @calculation.h %></p>
<p>K: <%= @calculation.k %></p>
<p>P: <%= @calculation.p %></p>
<p>A: <%= @calculation.a %></p>
<small>T: <%= @calculation.created_at %></small>
<br /><br />
    <%= @calculation.a_n %> <br />
    <% @amount = (@calculation.h * @calculation.k) %> 
    <% @percent = (@calculation.h * @calculation.k) / @calculation.p %> 
  <% for i in 0..@calculation.a do %> 
    <% @newAmount = ((@amount/(@percent)) + @amount) %>
    <%= "#{i}" + " - #{@amount}" %><br />
    <% @amount=@newAmount %>
  <% end %>
<script type="text/javascript" charset="utf-8">
  $(function() {
    new Highcharts.Chart({
      chart: {
    renderTo: "calculations_chart"
      },
      title: {
    text: "Sum for a year"
      },
      xAxis: {
    text: "Years"
      },
      yAxis: {
    title: {
      text: "Sum"
        }
      },
      series: [{
    data: //for loop?
      }]
    });
  });
</script>
<div id="calculations_chart" style="width:560px; height:300px;"></div>

1条回答
闹够了就滚
2楼-- · 2019-07-22 05:17

If you have a single value that was computed in a loop you can place it right in the location you want it

series: [{
data: [<%=@amount%>]
  }]

Or if you have a series of data stored somewhere you want to iterate over and add them to your chart

series: [
      {
      data: [
<% for i in 0..@calculation.a do %> 
  <% @amount = ((@amount/(@percent)) + @amount) %>
  <%= @amount %>,
<% end %>
 ]}
]

This is a lot of logic in the page, you might want to think about moving it to the controller or model. For super re usability in multiple places you can have a action that serves up the data in JSON that you get asynchronously in the pages that need it.

edited to match highchart format

查看更多
登录 后发表回答