问题
addToBasket = (id, qty) ->
if $.cookie('basket')?
# Basket exists
basket = $.parseJSON($.cookie('basket'))
basket.push( { 'id': id, 'qty': qty } )
$.cookie('basket', JSON.stringify(basket))
else
# Basket doesn't exist
alert 'Creating basket'
basket = JSON.parse([{'id': id, 'qty': qty}])
$.cookie('basket', JSON.stringify(basket))
I'm tearing my hair out; I cannot get the (compiled equivalent) function to run, always getting the illegal token error. I've checked for rogue, invisible characters and there's nothing besides CR/LFs in there.
回答1:
You're calling JSON.parse
on an array, which apparently qualifies as a syntax error instead of a normal exception due to the way browsers implement it. You're essentially doing this:
JSON.parse([{id: 123}].toString())
Which is the same as:
JSON.parse('[object Object]')
Which is illegal JSON, hence the error.
来源:https://stackoverflow.com/questions/14735557/unexpected-token-illegal-somewhere