当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Convert ruby array to java script array

问题描述:

I have a ruby code that will generate an array.I need to use that array in javascript.

<%= region.zip(min, max).select {|_, a, b| a == '0' && b == '0'}.map(&:first)%>;

This above code will generate an array like this

["A", "B", "C", "F", "H"]

Here is the demo http://repl.it/t03/680

I want to use this array in javascript. Below is what I tried and the error I got in console.

<script>

var output = <%= (region.zip(min, max).select {|_, a, b| a == '0' && b == '0'}.map(&:first)).gsub('"', '') %>;

</script>

Error is

SyntaxError: expected expression, got '&'

var output = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;F

Thanks

网友答案:

JSON is technically valid Javascript, so you could do something like:

 var output = <%= (region.zip(min, max).select {|_, a, b| a == '0' && b == '0'}.map(&:first)).map{|item| item.gsub('"', '')}.to_json %>;

And that should work as expected.

Note: I added the .to_json at the end of the Ruby code.

网友答案:

I used to do in the "standard" way, writing JS storing JSON in a variable, now I highly recommend to use: gon

It's great and allows you to handle with this situation easily, in your controller type:

gon.push({variable_name: [1,2,3]})

In your app layout use:

<%= include_gon %>
<!-- include your action js code -->

In your js you can just type:

console.log(gon.variable_name) // [1,2,3]
网友答案:

This is actually jeremy answer after modification.

 var output = <%= raw(region.zip(min, max).select {|_, a, b| a == '0' && b == '0'}.map(&:first).map{|item| item.gsub('"', '')}.to_json) %>
分享给朋友:
您可能感兴趣的文章:
随机阅读: