简体   繁体   English

javascript中以下两个有什么区别?

[英]what is the difference between the following two in javascript?

I am assigning php values to javascript as following 我正在为javascript分配php值,如下所示

var a = <?php echo 39; ?>

but javascript is throwing following error "Uncaught SyntaxError: Unexpected token ILLEGAL". 但是javascript引发了以下错误“Uncaught SyntaxError:Unexpected token ILLEGAL”。 When I am assigning php values in the following way then I am not getting any problem 当我以下列方式分配php值时,我没有遇到任何问题

var a = "<?php echo 39; ?>";

What I think is php code runs on server side first.So in the first case the php code is executed on server side first then that executed code is sent to the browser.So browser should see that code as(i think) 我认为php代码首先在服务器端运行。所以在第一种情况下,php代码首先在服务器端执行,然后执行的代码被发送到浏览器。所以浏览器应该看到代码为(我认为)

var a=39;

but instead of that it is throwing error.Why is it happening? 但不是这样,它会引发错误。为什么会发生这种情况?

您的第一个示例在javascript变量赋值结束时错过了分号:

var a = <?php echo 39; ?>; //<-- missing semicolon

First of all, it's best practice to always end your statements with a semicolon. 首先,最好用分号结束语句。 But regardless of the discussion in the other answers about where and when you should have one, there is also another very important difference in the two examples you have provided. 但无论在其他答案中讨论何时何地应该有一个答案,在你提供的两个例子中还有另一个非常重要的区别。

Example 1: 例1:

var a = <?php echo 39; ?>

Variable a is now an integer (no quotes): http://en.wikipedia.org/wiki/Integer_%28computer_science%29 变量a现在是一个整数 (没有引号): http//en.wikipedia.org/wiki/Integer_%28computer_science%29

Example 2: 例2:

var a = "<?php echo 39; ?>";

Variable a is now a string (quotes): http://en.wikipedia.org/wiki/String_%28computer_science%29 变量a现在是一个字符串 (引号): http//en.wikipedia.org/wiki/String_%28computer_science%29

I would say that the different between variable types is something you should be aware of. 我想说变量类型之间的差异是你应该注意的。 Especially in Javascript! 特别是在Javascript中!

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

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