【问题标题】:Stop javascript from implicitly converting string to int阻止 javascript 将字符串隐式转换为 int
【发布时间】:2016-10-26 03:16:46
【问题描述】:

所以我有一个带有字段date(string) 和count(integer) 的datapoint 对象。我正在尝试将它们添加到我的 show 视图中带有一些 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>

【问题讨论】:

  • dates.push( "&lt;%= c.date %&gt;" ) 用引号括起来使其成为字符串...否则2015-05-05 = 2005

标签: javascript ruby-on-rails ruby string type-conversion


【解决方案1】:

您缺少引号:

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 将其视为字符串原语,而不是数字和算术运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多