简体   繁体   English

Javascript /咖啡脚本附加TypeError:不是函数

[英]Javascript/Coffeescript append TypeError: is not a function

Why isn't working? 为什么不工作?

It works if I change variable msg for a string value. 如果我将变量msg更改为字符串值,则可以使用。

Code: 码:

console.log full_messages # Array [ "text to be displayed" ]
for msg in full_messages
  $('#error_explanation ul').append('<li>'+ msg +'</li>')

Error message: 错误信息:

TypeError: msg is not a function TypeError:msg不是函数

Your problem is in your whitespace (or lack thereof): 您的问题出在空白中(或缺少空白):

'<li>'+ msg +'</li>'

CoffeeScript thinks that the second + in that is a unary operator so the whole thing is interpreted as: CoffeeScript认为其中的第二个+是一元运算符,因此整个内容都解释为:

'<li>' + msg(+'</li>')

If you put spaces on both sides of your binary operators: 如果在二进制运算符的两侧都放置空格:

'<li>' + msg + '</li>'
#     ^^^   ^^^

then CoffeeScript does what you're expecting it to. 然后,CoffeeScript会执行您期望的操作。 Rule of Thumb : always put spaces on both sides of binary operators. 经验法则 :始终在二进制运算符的两侧放置空格。

You could also use string interpolation: 您还可以使用字符串插值:

"<li>#{msg}</li>"

That becomes exactly the same JavaScript as '<li>' + msg + '</li>' but is (arguably) more readable and idiomatic. 这与'<li>' + msg + '</li>'但(更具说服力)更具可读性和惯用性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM