代码之家  ›  专栏  ›  技术社区  ›  cluster1

在循环内或循环外声明变量/常量?

  •  1
  • cluster1  · 技术社区  · 6 年前

    // Creating the constant OUTSIDE the loop.
    const expected = "Some String";
    
    let expectedFound = result.some((element) => {
      return element.textContent === expected;
    });
    
    
    // Creating the constant WITHIN the loop.
    let expectedFound = result.some((element) => {
      const expected = "Some String";
    
      return element.textContent === expected;
    });

    只创建一次常量不是更好吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Zim    6 年前

    举个例子,在 some

    我会在办公室里拿申报单 一些

        2
  •  1
  •   Pablo Barría Urenda    6 年前

    从技术上讲,这不是一个循环,即使它在结构和功能上是相似的。JavaScript中的循环将是 for , for ... in for ... of while . 这些声明的主体是一个 . 例如:

    const expected = "Some String";
    let i = 0, expectedFound = false;
    while(i < result.length) {
        if(result[i].textContent === expected) {
            expectedFound = true;
            break;
        }
        i = i + 1;
    }
    

    some 方法。

    数组方法

    根据经验,我想说,如果您试图从JavaScript中挤出性能,那么使用优化循环可能比使用数组方法更好。但这是一个非常重要的问题 如果

    我在这件事上找到了一些阅读材料: https://hackernoon.com/javascript-performance-test-for-vs-for-each-vs-map-reduce-filter-find-32c1113f19d7