Is there a better way to do optional function parameters in JavaScript?

This question already has an answer here: Set a default parameter value for a JavaScript function 13 answers Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative if (typeof optionalArg === 'undefined') { optionalArg = 'default'; } Or an alternative idiom: optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg; Use whichever i

有没有更好的方法来在JavaScript中做可选的函数参数?

这个问题在这里已经有了答案: 为JavaScript函数设置默认参数值13个答案 如果传递了optionalArg,则逻辑将失败,但计算结果为false - 请尝试使用此替代方法 if (typeof optionalArg === 'undefined') { optionalArg = 'default'; } 或者另一种习语: optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg; 使用哪一种惯用语向你传达最好的意图! 我觉得这是最简单,最可读的方式: if (typ

How do I declare a namespace in JavaScript?

How do I create a namespace in JavaScript so that my objects and functions aren't overwritten by other same-named objects and functions? I've used the following: if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();} Is there a more elegant or succinct way of doing this? 我喜欢这个: var yourNamespace = { foo: function() { }, bar: function() { } }; .

我如何在JavaScript中声明一个名称空间?

如何在JavaScript中创建一个名称空间,以便我的对象和函数不会被其他同名对象和函数覆盖? 我使用了以下内容: if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();} 有没有更优雅或简洁的方式来做到这一点? 我喜欢这个: var yourNamespace = { foo: function() { }, bar: function() { } }; ... yourNamespace.foo(); 我使用Enterprise jQuery网站上的方法: 以下是他们的示

Why are functions in JavaScript set to global variables instead of plain functions?

I am wondering if anyone knows why some people define global variables that are set to functions vs just defining a global function name. For example: var foo = function() { alert('hello!'); } instead of function foo() { alert('hello!'); } Wouldn't the second method be better since there is a chance something might overwrite the first variable and you would lose the function? Does this

为什么JavaScript中的函数设置为全局变量而不是普通函数?

我想知道是否有人知道为什么有些人定义了设置为函数的全局变量而仅定义了全局函数名。 例如: var foo = function() { alert('hello!'); } 代替 function foo() { alert('hello!'); } 第二种方法不会更好,因为有可能会覆盖第一个变量,你会失去这个功能吗? 这与扩展对象有什么关系吗? 是否有性能问题?

Function Declarations Within Blocks according to the Google JavaScript style guide

According to the Google JavaScript style guide, function declarations should not be declared within blocks since this is not a part of ECMAScript. However, I'm not entirely clear on what counts as a block. Specifically, I have a constructor function and I want to define a function within the scope of that constructor. Would this count as a function within a block, since it is within a set

根据Google JavaScript风格指南在块内的函数声明

根据谷歌JavaScript风格指南,函数声明不应在块内声明,因为这不是ECMAScript的一部分。 然而,我不完全清楚什么是一个区块。 具体来说,我有一个构造函数,我想在该构造函数的范围内定义一个函数。 这是否会作为块内的函数计算,因为它在一组{?}内。 如果是这样,这是否意味着每个函数声明都必须是全局的? 一些代码的好处: 错误(?) function Constructor() { function Shout () { alert('THE BEST UX IS IN

How to replace all occurrences of a string in JavaScript?

I have this string: "Test abc test test abc test test test abc test test abc" Doing str = str.replace('abc', ''); seems to only remove the first occurrence of abc in the string above. How can I replace all occurrences of it? For the sake of completeness, I got to thinking about which method I should use to do this. There are basically two ways to do this as suggested by the other answers

如何在JavaScript中替换所有出现的字符串?

我有这个字符串: "Test abc test test abc test test test abc test test abc" 干 str = str.replace('abc', ''); 似乎只能删除上面字符串中第一次出现的abc 。 我怎样才能取代它的所有事件? 为了完整起见,我不得不考虑使用哪种方法来完成此操作。 根据本页其他答案的建议,基本上有两种方法可以做到这一点。 注意:通常,不推荐使用JavaScript扩展内置原型。 为了说明的目的,我在String原型上作为扩展提供,在St

How to validate an email address in JavaScript?

如何在JavaScript中验证电子邮件地址? Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium) function validateEmail(email) { var re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } Here

如何验证JavaScript中的电子邮件地址?

如何在JavaScript中验证电子邮件地址? 使用正则表达式可能是最好的方法。 你可以在这里看到一堆测试(从铬中获得) function validateEmail(email) { var re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } 以下是接受unicode的常规表达式示例: var

Create GUID / UUID in JavaScript?

I'm trying to create globally-unique identifiers in JavaScript. I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc.. The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around. There have been a couple attempts at this. The question

在JavaScript中创建GUID / UUID?

我试图在JavaScript中创建全局唯一标识符。 我不确定在所有浏览器上都有哪些例程可用,如何“随机”并播种内置的随机数生成器等等。 GUID / UUID应至少为32个字符,并应保留在ASCII范围内以避免在传递时遇到麻烦。 这方面曾有过几次尝试。 问题是:你想要实际的GUID,还是只是看起来像GUID的随机数字? 生成随机数很容易。 function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000)

Retrieve the position (X,Y) of an HTML element

我想知道如何在JavaScript中获取HTML元素(如img和div的X和Y位置。 The correct approach is to use element.getBoundingClientRect() : var rect = element.getBoundingClientRect(); console.log(rect.top, rect.right, rect.bottom, rect.left); Internet Explorer has supported this since as long as you are likely to care about and it was finally standardized in CSSOM Views. All other browsers adopted it a lo

检索HTML元素的位置(X,Y)

我想知道如何在JavaScript中获取HTML元素(如img和div的X和Y位置。 正确的方法是使用element.getBoundingClientRect() : var rect = element.getBoundingClientRect(); console.log(rect.top, rect.right, rect.bottom, rect.left); 只要您可能关心,并且最终在CSSOM视图中标准化了,Internet Explorer就已经支持这一功能。 所有其他浏览器很久以前就采用了它。 某些浏览器也会返回高度和宽度属性,虽然这是非标准的。 如

How do I detect a click outside an element?

I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area. Is something like this possible with jQuery? $("#menuscontainer").clickOutsideThisElement(function() { // Hide the menus }); NOTE: Using stopEventPropagation() is something that should be avoided as it breaks

如何检测元素外的点击?

我有一些HTML菜单,当用户点击这些菜单的头部时,我会完全显示这些菜单。 当用户点击菜单区域外时,我想隐藏这些元素。 是这样的jQuery可能吗? $("#menuscontainer").clickOutsideThisElement(function() { // Hide the menus }); 注意:使用stopEventPropagation()是应该避免的,因为它会打破DOM中的正常事件流。 有关更多信息,请参阅此文章。 考虑使用这种方法。 将单击事件附加到关闭窗口的文档主体。 将一个

Is there an "exists" function for jQuery?

How can I check the existence of an element in jQuery? The current code that I have is this: if ($(selector).length > 0) { // Do something } Is there a more elegant way to approach this? Perhaps a plugin or a function? In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 (and NaN) means false , everything else true . So you could write: if ($(selecto

jQuery有没有“存在”功能?

我如何检查jQuery中是否存在元素? 我现在的代码是这样的: if ($(selector).length > 0) { // Do something } 有没有更好的方法来解决这个问题? 也许是一个插件或功能? 在JavaScript中,一切都是'真的'或'虚假的',而对于数字0 (和NaN)则意味着false ,其他所有事情都是true 。 所以你可以写: if ($(selector).length) 你不需要>0部分。 是! jQuery.fn.exists = function(){ return