psychopy.org | Reference | Downloads | Github

Code segment won't translate to JS

I have a code segment that I adapted from another project. The code window is set to Auto -> JS as I plan to run my study online. In the builder view’s code editor, I get the error “/* Syntax Error: Fix Python code */”. My knowledge of python and JS is super limited though so I’m not sure what the error is when it tries to translate from python to JS. I was hoping someone could help me out.

Here is the code.

def clickCount(clicked, box):
    #Return the list indices of a box
    return [i+1 for i, x in enumerate(clicked) if x == box]

Thanks in advance!

Posting here to move to current thread.

So your code looks like this now?

function clickCount(clicked, box){
    #Return the list indices of a box
    for [i, x] of clicked.entries() {
    if (x == box){
    return i+1
    }
  }
}

I am not an expert in JS myself, just learning things as I go along, but this looks like it should work. Let us know if this works for you.

It did not work unfortunately. However, I did just look up an alternative method for enumeration without using enumerate() and came up with this, which I think is a step in the right direction, but it still returns “none” when I click one of the boxes on my screen.

def clickCount(clicked, box):
    #Return the list indices of a box
    for i in range(len(clicked)): 
        if x == box:
            return i + 1```

I just fixed my problem. Here is the working code

def clickCount(clicked, box):
    #Return the list indices of a box
    for i in range(len(clicked)): 
        if clicked[i] == box:
            return i + 1

I think I remember struggling with ennumerate, but I changed strategies so I didn’t have to deal with it anymore. Glad you found something that worked! You can mark your post as the solution.