为什么我们在javascript中使用const for for ... of循环?

时间:2020-07-03 17:13:17

标签: javascript for-of-loop

我想知道为什么我们在JavaScript def bincount2D(id_ar_2D, weights_1D, sz=None): # Inputs : 2D id array, 1D weights array # Extent of bins per col if sz == None: n = id_ar_2D.max() + 1 N = len(id_ar_2D) else: n = sz[1] N = sz[0] # add offsets to the original values to be used when we apply raveling later on id_ar_2D_offsetted = id_ar_2D + n * np.arange(N)[:, None] # Finally use bincount with those 2D bins as flattened and with # flattened b as weights. Reshaping is needed to add back into "a". ids = id_ar_2D_offsetted.ravel() W = np.tile(weights_1D, N) return np.bincount(ids, W, minlength=n * N).reshape(-1, n) 循环中使用const。我看到的每个使用for...of循环的示例在声明变量时都使用for...of。例如:

const

我们有没有理由不使用for (const item of array) { // do something }

var

谢谢

1 个答案:

答案 0 :(得分:2)

var将变量加载到全局范围中,而letconst将在词法范围中声明该变量:

const test = [1, 2, 3];

// lexical
for (let testItem of test) {
    console.log(window.testItem);
}

// global
for (var testItem of test) {
    console.log(window.testItem);
}