0

My Code is:

<script type="text/javascript">
  var clicky_custom = clicky_custom || {};
  clicky_custom.visitor = {
    username: 'bobjones',
    email: 'bob@jones.com'
  };
  clicky_custom.visitor_keys_cookie = ['username', 'email'];
</script>

You know how if you are adding another line, you need to put a comma on all the lines except for the last one? For example, the comma which appears under bob. How do I only add a comma if it is not the last line?

Damainman
  • 515
  • 9
  • 21
  • 3
    If you're using PHP to create Javascript literals, you should use `json_encode()` rather than trying to write it yourself. – Barmar Oct 27 '13 at 04:02
  • If generating a comma-separated list in a loop I would normally just add a comma on every iteration and then after the loop take a substring of the result minus the last character. But if the language can do it for you (e.g., with `json_encode()`) take that option as a first preference. – nnnnnn Oct 27 '13 at 04:04

1 Answers1

0

First of all, for objects, in ES5, you can leave a trailing comma. Check out this answer for more information.

As for your question, it really depends on how the information is coming to you. One thing you could do is implode an array with a comma separator. However, your best bet would be to encode your PHP arrays as JSON objects using json_encode, which will work fine as Javascript objects. That function will output a string that you could drop directly into your script.

Community
  • 1
  • 1
Evan
  • 825
  • 4
  • 14
  • 1
    _"First of all, for objects, in ES5, you can leave a trailing comma."_ - Though there are still plenty of IE8 users out there, so... – nnnnnn Oct 27 '13 at 04:09
  • You're right, of course! Just thought it was relevant information. – Evan Oct 27 '13 at 05:05