作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
是否有必要检查代码中的所有参数和其他条件,如果我知道,我永远不会传递错误的参数,它应该可以正常工作(假设我已经在该代码之外进行了一些检查)。
示例:
这段代码:
/**
* Applies function to all elements of array in specified
* context.
* If array is empty, returns null.
*/
MyNameSpace.foreach = function(arr, callback, context) {
if (!(arr instanceof Array)) {
throw new Error('first argument is not an array');
}
if (typeof callback !== 'function') {
throw new Error('callback is not a function');
}
if (typeof arr.length === 'undefined') {
throw new Error('Length undefined');
}
var con = typeof context === 'object' ? context : window;
var i = arr.length;
if ( i <= 0 ) {
return null;
}
for ( j = 0; j < i; j++ ) {
callback.call(con, j, arr[j]);
}
}
可能是:
MyNameSpace.foreach = function(arr, callback, context) {
var con = typeof context === 'object' ? context : window;
var i = arr.length;
if ( i <= 0 ) {
return null;
}
for ( j = 0; j < i; j++ ) {
callback.call(con, j, arr[j]);
}
}
最佳答案
这绝对是一个很好的做法。它可以提高应用程序的稳定性并帮助调试。缺点是它会使代码变得困惑(使其难以阅读),并且会影响性能(尽管对于大多数 JavaScript 应用程序来说,性能并不重要)。
你必须针对每种情况采取看法。这实际上取决于(1)参数不正确的可能性有多大以及(2)如果参数不正确将会造成多大的损害。
关于javascript - 在仅供内部使用的代码中进行额外检查是否是一种好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5603935/
我只想知道如何使文件只对特定组可执行。 我有一个具有此权限的文件 /bin/ping rwxr-xr-x root root 34248 oct 14 2010 /bin/ping 例如,如何使它只对
我在 mysql 中有一个正则表达式,想反转它。但不想使用 NOT REGEXP。否定回顾 (?![something]) 在 mysql 中不起作用。确切地说,我想仅使用 REGEXP 查找不为 -
我有一个应用程序,我们正在使用它来为另一个应用程序提供 API 调用。然而它感觉很重,因为它仍在使用整个 rails ,但我们不使用 View 等... 其他人是如何解决这个问题的,只是删除文件?我所
我是一名优秀的程序员,十分优秀!