Unexpected token ILLEGAL .. somewhere

谁说胖子不能爱 提交于 2020-01-15 03:28:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!