删除方法中的冗余代码

remove redundant code in method

我使用了以下有效的代码,但在阅读了有关 JS 的内容后(我还很新)我注意到了 3 件事。

  1. 在方法的开头使用return

  2. 使用ternary条件(不确定在这种情况下如何使用它)

  3. 使用 reduce(对此不确定,但也许可以代替 forEach)

是否可以在下面的代码中使用它?

 get: function(document, oData) {
        var self = this;
        var oInnerHTML;
        if (oData) {
            var oParsedHTML = this._parseHtml(document);
            oInnerHTML = oParsedHTML;
            oData.forEach(function(configEntry) {
                oInnerHTML = self._routeExtentionTypes(configEntry, oInnerHTML);
            });
            oInnerHTML = this._convertBackToHtml(oInnerHTML);
        } else {
            oInnerHTML = document;
        }
         return oInnerHTML
    }

代码所做的是

  1. getting HtmlString and parse it
  2. extend it according to the cofigEntry and the original HTML
  3. when the config entry was done it convert back to HTML

我想,你可以试试 Array#reduce()

基本上,reduce 正在执行您想要的操作。它需要一个起始值并根据需要迭代一个数组和 returns 一些值。

原代码

var oParsedHTML = this._parseHtml(document);
    oInnerHTML = oParsedHTML;
oData.forEach(function(configEntry) {
    oInnerHTML = self._routeExtentionTypes(configEntry, oInnerHTML);
});

转换为

this._convertBackToHtml(oData.reduce(function (r, configEntry) {
    return self._routeExtentionTypes(configEntry, r);
}, this._parseHtml(document))) :

因为起始值现在是 this._parseHtml(document),不需要额外的变量,return 值成为下一次迭代的新输入值。

get: function (document, oData) {
    var self = this;
    return oData ?
        this._convertBackToHtml(oData.reduce(function (r, configEntry) {
            return self._routeExtentionTypes(configEntry, r);
        }, this._parseHtml(document))) :
        document;
}

在方法开头使用return

当您的对象准备好并具有所需的值时,请使用 return。尽早 return 是个好习惯。这样可以执行和评估最少量的代码。

在上面的例子中“oInnerHTML”变量准备好满足某些条件的值,所以在这种情况下你可以return它一旦object/variable 准备好价值。

使用三元条件

当您根据简单条件为变量赋值或者您正在做出多个结果非常简短的决策时,三元运算符很常见。例如

x ? y: z

在上面的例子中,三元运算符可以如下使用:(请执行代码并仔细检查)

get: function(document, oData) {
  var self = this;      
  return (oData) ? document : get_oInnerHTML(oData);
}      

function get_oInnerHTML (oData){
  var oInnerHTML;
  oData.forEach(function(configEntry) { oInnerHTML = self._routeExtentionTypes(configEntry, this._parseHtml(document)); });
  return oInnerHTML;
}  

以上代码在三元条件下使用了一个函数。由于有很多行需要在条件内执行,所以我为它创建了单独的函数并在条件下使用。

使用减少

reduce() 方法对累加器和数组的每个值(从左到右)应用函数以将其减少为单个值。

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) { return previousValue + currentValue; });