Org-mode JavaScript code block evaluation error when using console.log - javascript

I receive the error Invalid read syntax: "]" when using console.log to print values from JavaScript array objects inside of org file code blocks. Arrays that contain strings produce this error. Arrays which have just numeric values print to the console fine.
I am not sure why org-babel is having difficulty with console.log(). I tried checking the encoding of my org file as a first step. I verified my code using node.js by itself. Specifying a different interpreter (e.g babel-cli) to evaluate the code block produces the same error.
This works
#+BEGIN_SRC js
let myarray = [1, 2, 3, 4, 5];
console.log(myarray);
#+END_SRC
#+RESULTS:
: [1 (\, 2) (\, 3) (\, 4) (\, 5)]
This does not
#+BEGIN_SRC js
let myarray = ["a", "b", "c", "d", "e"];
console.log(myarray);
#+END_SRC
Is there something I need to do within my org config files? I am using Emacs version 26.1 on Windows 7 (build 1, x86_64-w64-mingw32). Node.js is version 10.15.3 .

Correction:
Where I have different lines trying to return/show values inside a code block, only the first return statement produces a result (return ends the immediate scope). What seems to work is process.stdout.write('yourcodehere'+ '\n');
Example:
Trying to use multiple return statements
#+BEGIN_SRC js
return ([0,1,2,3,4]);
return ([5,6,7,8,9]);
#+END_SRC
#+RESULTS:
| 0 | 1 | 2 | 3 | 4 |
Using process.stdout.write()
#+BEGIN_SRC js
process.stdout.write([0, 1, 2, 3, 4] + '\n');
process.stdout.write(["a", "b", "c", "d", "e"] + '\n');
#+END_SRC
#+RESULTS:
: 0,1,2,3,4
: a,b,c,d,e
: undefined
Previous Message:
Ok, I found a simple solution. Use return instead of
console.log().I tried the same example in Python and only got results when using return instead of print. So I tried the same with
my JavaScript examples using return as the final step and this works
great. The formatting of the array in the results block looks better
too.

Related

Safety of passing python list to javascript through jinja template

Just like the question posed here, I have a list in one of my Flask app's routes:
my_list = ['a', 'b', 'c']
The number of elements in the list depends on user input, but the elements themselves are strings from elsewhere in the program that the user doesn't have control over. I'm wondering whether it's safe to use this list in a <script></script> tag in my template. I'm using the python list as a javascript array using the tojson filter. This works in my development server just fine, but my code editor is pointing out 6 problems.
$(document).ready(function() {
var my_array = {{ my_list|tojson }};
for (let index = 0; index < my_array.length; index++) {
console.log(my_array[index]);
}
});
Property assignment expected. [line 2]
',' expected. [line 2]
',' expected. [line 2]
')' expected. [line 2]
Declaration or statement expected. [line 6]
Declaration or statement expected. [line 6]
Is this just erroneous flagging from my linter or do I need another way to use the python list in my javascript? Wondering whether this will cause any security issues when I deploy the app.

Javascript - List (array) length and getting an item from the list not working

I'm practicing JavaScript (just started this week) on vscode with the Quokka.js extension. Right now I'm initializing a list called "things" and trying to get the length of the list and getting some items out of it. This is my code:
var things = ['bananas', 'apples', 7];
things.length;
things[0];
The last two rows return nothing to me, not even "undefined".
How do I get vscode to return the length and the first object from the list using [0]? If it is not possible in vscode, what program should I use for learning JavaScript?
I also tried initializing the list as an array with
Array things = ['bananas', 'apples', 7];
but this does not seem to be allowed.
Moreover, for example the command
things.splice
seems to work in vscode.
Even if you're using Quokka, it's better to output using console.log. Quokka works very well with console.log.
Also try not to use var or declare array using Array. This is JavaScript, not Java.
// Do not use var
let things = ['bananas', 'apples', 7];
console.log(things.length);
console.log(things[0]);
// This will not work
// This does not make any sense either
Array things = ['bananas', 'apples', 7];
JavaScript Array is not Class or an interface by using which you can declare it's instances. JavaScript Array is a global object. There are no classes in JavaScript.

How to pass an array of integers as a parameter from javascript to python?

I have a javascript code that obtains the value of several checked boxes and inserts their value (integers) into an array:
var my_list = $('.item:checked').map(function(){return $(this).attr('name');}).get();
I want to pass this javascript array to a python function as a paramter. This is how I am doing it right now, with ajax and jQuery:
$.ajax({
url : "{{tg.url('/foo/bar')}}",
data : {
my_list: JSON.stringify(my_list),
...
},
On the python side, I have this code, to get the parameters:
item_list = get_paramw(kw, 'my_list', unicode)
This works, but I am not receiving the array as an array of integers, but as a single string containing the "[", "]", "," and """ symbols, which I would have to parse and isn't the most elegant way of dealing with this whole situation I think.
How should it be done to receive a javascript array of integers as an array of integers in python (not as a string)?
The easiest way to send simple arbitrarily-structured data from Javascript to Python is JSON. You've already got the Javascript side of it, in that JSON.stringify(my_list). All you need is the Python side. And it's one line of code:
item_list_json = get_paramw(kw, 'my_list', unicode)
item_list = json.loads(item_list_json)
If item_list in your JS code were the Javascript array of numbers [1, 2, 3, 4], item_list in your Python code would be the Python list of ints [1, 2, 3, 4].
(Well, you also have to import json at the top of your script, so I guess it's two lines.)
The proper way to send multiple values for one key is
data: {
my_list: my_list,
},
traditional: true
...
Suppose my_list = [ 1, 2, 3 ], this results a query string / POST data
my_list=1&my_list=2&my_list=3
Without the traditional flag, the result would be
my_list[]=1&my_list[]=2&my_list[]=3
Which of course works, but in TurboGears you need to access it as my_list[].
On the other hand, I am not sure if the TG keyword argument passing work with multiple values; if you get a single value in kw, you can use request.getall('foo') to return all the foo keys as a list (possibly an empty list).

Checking value exists in an array position

I have a large array called "data".
At the 10th array position i have this at its data value:
[10] => 1,2
Now what im trying to do in JS is something like this:
i = 1;
if(i in data[10]){
//great success, very nice!
}
I thought comma separated data might act like an array with the "IN" method, but its not working. I get this error:
Uncaught TypeError: Cannot use 'in' operator to search for '1' in 1,2
What would be the correct solution for my problem ?
You don't show the code for how you assign 1,2 to data[10]. The value of 1,2 is simply 2 as you can see from executing the following in a JavaScript shell/console. See the reference for how the comma operator works.
However, the error message you are getting suggests that you have the string"1,2". To turn it into an array, you should use split() as in:
> data[10] = "1,2"
1,2
> data[10].split(',')
[ "1", "2" ]
To iterate over the values you can use the in operator on the resulting Array as in:
var data = new Array();
data[10] = '1,2';
var valueArray = data[10].split(',');
for (var i in valueArray) {
alert('valueArray[' + i + '] is ' + valueArray[i]);
}
You can run this in a browser console and the alert will show you two messages:
valueArray[0] is 1
valueArray[1] is 2
Note that you don't need to initialize i before the loop begins. The inoperator will do this automatically. Also, it's good practice to use local variables hence the var i in the code above.
On a side note, if you are new to JS but you need to deal with a lot of data structure manipulation, it's worth learning about underscore.js. Take a look at _.each() in particular. Underscore can save you from writing a lot of looping logic.
If, however, you want to do a membership check then you need to use not in but Array.indexOf(). See http://jsfiddle.net/nRS9m for an example forked from your jsfiddle in the comments. More examples:
> valueArray
[ "1", "2" ]
> valueArray.indexOf("3")
-1
> valueArray.indexOf("1")
0
> valueArray.indexOf("2")
1
> valueArray.indexOf(1)
-1
> valueArray.indexOf((1).toString())
0

eval json data get different length in IE and firefox

I got json data from the server by ajax:
request.responseText=[{name:xxx},{name:xxx},{name:xx}].
Then I use the
var data=eval(request.responseText);
alert(data.length);
In IE,it is "4",while in Firefox it is "3".
Use the IE debugger I found that the element in data is like:
[Methods]
[0]
[1]
[2]
So itis length is 4.
I wonder why?
My guess is that the server returned data with a trailing comma, for example:
[1, 2, 3, ]
In IE, this array will be interpreted as having a length 4, while in standard compliant browsers, it will have a length 3.
[Methods] is a separate node shown by the debugger to separate functions from other values.
It does not actually exist in the object.
If an array has three items named 0, 1, and 2, its length will be 3.

Categories

Resources