何时在Javascript和jQuery中使用括号,括号和花括号 [英] When to use parentheses, brackets, and curly braces in Javascript and jQuery

查看:133
本文介绍了何时在Javascript和jQuery中使用括号,括号和花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript和jQuery中使用括号,括号和花括号时,我有点困惑。有没有一种简单的方法可以理解何时何时使用这些?

I'm a bit confused when using some of parentheses, brackets, and curly braces in Javascript and jQuery. Is there a simple way of understanding when to distinguish when to use these?

示例1:

$("#theDiv").animate({width: "500px" }, 1000);

示例2:

$("img").attr({src: "/images/hat.gif", title: "jQuery"});

示例3:

$('a[rel="nofollow self"]')

谢谢。

推荐答案

不幸的是,最好的答案是在必要时适当地使用它们。

Unfortunately, the best answer is "use them each as appropriate where necessary".

JavaScript中的括号()用于函数调用,包围条件语句或用于分组以强制执行Order操作。

Parenthesis () in JavaScript are used for function calls, to surround conditional statements, or for grouping to enforce Order of Operations.

function myFunc() {
  if (condition1) {

  }
  if ( (1 + 2) * 3) {
    // very different from (1 + 2 * 3)
  }
}

大括号 {} 在对象文字声明期间使用,或者用于封闭代码(函数定义,条件块,循环等)。

Braces {} are used during the declaration of Object Literals, or to enclose blocks of code (function definitions, conditional blocks, loops, etc).

var objLit = {
  a: "I am an Object Literal."
};

括号 [] 通常是 主要用于访问Object(或Array的元素)的属性,因此 mylist [3] 获取数组中的第四个元素。

Brackets [] are typically mostly used for accessing the properties of an Object (or the elements of an Array), so mylist[3] fetches the fourth element in the Array.

var mylist = [1,2,3,4];
alert(mylist[2]);

你试图从jQuery开始也没有用,jQuery也使用自己的Selector字符串中的语法传递给函数调用(可以使它看起来比实际复杂得多)。这个: $('a [rel =nofollow self]')只是一个函数调用,内部括号由jQuery处理。

It doesn't help that you're trying to start with jQuery, which also uses its own Selector Grammar within Strings that are passed to function calls (which can make it look much more complicated than it actually is). This: $('a[rel="nofollow self"]') is only a single function call, and the inner brackets are handled by jQuery.

这篇关于何时在Javascript和jQuery中使用括号,括号和花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆