简体   繁体   中英

Getting each i element of a ruby array in a javascript function (escaping and unescaping)?

Say, in ruby I've got an array: ruby_array = [1, 2, 3, 4, 5]

In my javascript script, I want to be able to push every element from my ruby_array to a javascriptArray :

var javascriptArray = [];

for (i = 0; i < <%= raw ruby_array.size %>; i++) {
   alert("The " + i + ". element of my ruby array is: " + <%= raw ruby_array[i] %>);
   // Problem: I guess, I cannot get the i javascript variable when calling ruby_array[i]
   // How do I unescape the i?

   // Now push every ruby_array element into my javascriptArray
   // Same problem like above
   javascriptArray[i] = Number(<%= raw ruby_array[i] %>);
}

The error message I get is:

SyntaxError: expected expression, got ')'

Note: If I leave the [i] in ruby_array[i] out, the output is fine:

The 0. element of my ruby array is: 1,2,3,4,5

...

The 4. element of my ruby array is: 1,2,3,4,5

I've also tried .to_json.html_safe with the same results. So how do I get the i-th element from my ruby array in javascript code?

Both of these will escape js.

You can try:

var javascriptArray = <%= escape_javascript ruby_array.to_json %>

or

var javascriptArray = <%= j ruby_array.to_json %>

我没有测试过,但这应该可以工作

var javascriptArray = [<%= j(ruby_array.join(',')) %>];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM