Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript使用Try-Catch或If-Else提高性能_Javascript_If Statement_Try Catch - Fatal编程技术网

JavaScript使用Try-Catch或If-Else提高性能

JavaScript使用Try-Catch或If-Else提高性能,javascript,if-statement,try-catch,Javascript,If Statement,Try Catch,我正在试验深层对象树的数据,现在我想我的代码分解现在 很多时候,我必须检查是否存在整个分支来设置或取消设置中的值。我使用了很多“if-else”条件,我正在考虑使用函数 例如,要在分支中将值设置为false,我可以有两种解决方案,如: function setFalse(root, /* [names]* */) { ... // If root exists, call setFalse() with the rest of arguments. // Else if I on

我正在试验深层对象树的数据,现在我想我的代码分解现在

很多时候,我必须检查是否存在整个分支来设置或取消设置中的值。我使用了很多“if-else”条件,我正在考虑使用函数

例如,要在分支中将值设置为false,我可以有两种解决方案,如:

function setFalse(root, /* [names]* */) { ...
    // If root exists, call setFalse() with the rest of arguments.
    // Else if I only have two arguments : root[arguments[1]] = false ;
    // Else return.
... }
或者使用try-catch:

function setFalse(root, /* [names]* */) {
    try {
        var l = arguments.length,
            branch = root ;
        for (var i=1 ; i<l-1 ; i++) // Not taking the last argument.
            branch = branch[arguments[i]] ;
        branch[arguments[l-1]] = false ; // With last argument.
    }
    catch(e) {}
}
函数setFalse(根,/*[名称]**/){
试一试{
var l=arguments.length,
分枝=根;

对于(var i=1;i两者都不是。第一种方法效率低下,因为它将创建大量数组来处理参数;第二种方法效率低下,因为错误处理通常是一种昂贵的流控制方法

使用第二个原则,但检查每个级别是否存在属性,而不是依赖错误处理:

function setFalse(root /* ,[names] */) {
  var l = arguments.length, branch = root;
  for (var i = 1 ; i < l-1 ; i++) {
    if (!branch.hasOwnProperty(arguments[i])) return;
    branch = branch[arguments[i]];
  }
  if (branch.hasOwnProperty(arguments[l-1])) {
    branch[arguments[l-1]] = false;
  }
}
函数setFalse(root/*,[names]*/){
var l=arguments.length,branch=root;
对于(变量i=1;i

演示:

太好了!谢谢你的回答。我最终离正确的方法不远了。