所以我有一个 datapoint
对象,其中包含字段 date
(字符串)和 count
(整数)。我试图将它们添加到数组中,并在我的 show
View 中使用一些 JS。一切都运行良好 - 除了我的 date
字符串被转换为一系列 JS 算术。例如:“2015-05-05”
值将转换为 2005
。代码如下:
<h1 id="chart"></h1>
<script language="javascript" type="text/javascript">
var counts = ['Count']
var dates = ['x']
<% @chart.datasource.datapoints.each do |c| %>
dates.push( <%= c.date %> )
counts.push( <%= c.count %> )
<% end %>
chart(counts, dates);
</script>
最佳答案
您缺少引号:
var counts = ['Count']
var dates = ['x']
<% @chart.datasource.datapoints.each do |c| %>
dates.push( "<%= c.date %>" )
counts.push( <%= c.count %> )
<% end %>
chart(counts, dates);
将值括在引号中将强制 JS 将其视为字符串基元,而不是数字和算术运算符。
关于javascript - 阻止 javascript 将 string 隐式转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37997529/