有问题的代码在这里:
var $item = $(this).parent().parent().find('input');
在变量名中使用美元符号的目的是什么,为什么不直接排除它呢?
有问题的代码在这里:
var $item = $(this).parent().parent().find('input');
在变量名中使用美元符号的目的是什么,为什么不直接排除它呢?
当前回答
let $ = "Hello";
let $$ = "World!";
let $$$$$$$$$$$ = $ + " " + $$;
alert($$$$$$$$$$$);
这将显示一个“Hello World!”警告框。
正如您所看到的,$只是JavaScript标识符或变量名的一个普通字符。事实上,您可以使用大量Unicode字符作为变量名,使其看起来像美元或其他货币符号!
注意,$符号也被用作jQuery名称空间/库的引用:
$("p").text("I am using some jquery");
// ...is the same as...
jQuery("p").text("I am using some jquery");
$也用于新的模板文字格式,使用JavaScript ES6/2015版本支持的字符串插值:
var x = `Hello ${name}`;
其他回答
美元符号在ecmascript 2015-2016中用作“模板文字”。 例子:
var a = 5;
var b = 10;
console.log(`Sum is equal: ${a + b}`); // 'Sum is equlat: 15'
下面是工作示例: https://es6console.com/j3lg8xeo/ 注意这个符号" ' ",它不是普通的引号。
你也可以在使用jQuery库时遇到$。
$ sign在正则表达式中表示行结束。
这里有一个很好的短视频解释:https://www.youtube.com/watch?v=Acm-MD_6934
According to Ecma International Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1). The Unicode identifier grammar is based on both normative and informative character categories specified by the Unicode Standard. The characters in the specified categories in version 3.0 of the Unicode standard must be treated as in those categories by all conforming ECMAScript implementations.this standard specifies specific character additions:
美元符号($)和下划线(_)允许出现在IdentifierName中的任何位置。
进一步阅读可以在http://www.ecma-international.org/ecma-262/5.1/#sec-7.6上找到
Ecma国际是成立于1961年的行业协会,致力于信息通信技术(ICT)和消费电子产品(CE)的标准化。
变量中的'$'对于解释器来说没有任何特殊意义,就像下划线一样。
据我所知,许多使用jQuery的人(在我看来,您的示例代码就是这样的)倾向于在包含jQuery对象的变量前面加上$,这样它们就很容易被识别,不会与整数混淆。
jQuery中的美元符号函数$()是一个经常使用的库函数,因此最好使用较短的名称。
我可能会补充说,使用它的jQuery可以让你做这样的事情,例如:
$.isArray(myArray);
美元符号就像一个普通的字母或下划线(_)。它对解释器没有特别的意义。
与许多类似的语言不同,Javascript中的标识符(如函数名和变量名)不仅可以包含字母、数字和下划线,还可以包含美元符号。它们甚至可以以美元符号开头,或者只由美元符号组成,没有其他符号。
因此,$在Javascript中是一个有效的函数或变量名。
为什么要在标识符中使用美元符号?
该语法并没有真正强制在标识符中使用美元符号的任何特定用法,因此取决于您希望如何使用它。在过去,通常建议只在生成的代码中以美元符号开始标识符——也就是说,不是手工而是由代码生成器创建的代码。
然而,在你的例子中,情况似乎并非如此。看起来好像有人只是为了好玩才在开头放了一个美元符号——也许他们是PHP程序员,出于习惯才这么做的,或者别的什么。在PHP中,所有变量名前面都必须有一个美元符号。
There is another common meaning for a dollar sign in an interpreter nowadays: the jQuery object, whose name only consists of a single dollar sign ($). This is a convention borrowed from earlier Javascript frameworks like Prototype, and if jQuery is used with other such frameworks, there will be a name clash because they will both use the name $ (jQuery can be configured to use a different name for its global object). There is nothing special in Javascript that allows jQuery to use the single dollar sign as its object name; as mentioned above, it's simply just another valid identifier name.