【问题标题】:Why cant I reassign this variable to a new value in node.js?为什么我不能将此变量重新分配给 node.js 中的新值?
【发布时间】:2018-12-21 04:00:58
【问题描述】:

我知道选择排序算法不正确。现在很好,但是为什么 我可以不将 iMinimum 分配给 j for 循环内的 j 吗? 我正在使用节点版本 10+。 console.log “iMinimum is now ...” 显示了前面分配的变量的值,所以我很困惑。

 console.log('SELECTION SORT')

let data = [5,1,3,9,4]

for(let i = 0; i < data.length; i++){
 iMinimum = i


for(let j = iMinimum+1; j < data.length; j++){
     console.log(`j is now ${j}`)
     if(data[j] < data[iMinimum]){
         iMininum = j
         console.log(`iMinimum is now ${iMinimum} and j is ${j}`)
     }
}
data[i] = data[iMinimum] 
}

console.log(`Sorted Array: ${data}`)

【问题讨论】:

  • 错字 iMininum vs iMinimum
  • omgggg 谢谢我认为解释器会给我一个未定义的错误。为什么没有呢??
  • @Prasanna 已标记
  • 您在那里声明了一个全新的变量。就像你在上面对iMinimum = i 所做的那样。
  • @Prasanna 谢谢……是时候告诉人们删除这个问题了,哈哈

标签: javascript node.js algorithm


【解决方案1】:

您有一些拼写错误,请注意 iMininumiMinimum

要让解释器警告您未声明的变量,请以

开头
'use strict';

这将启用strict mode,强制您声明所有变量。

要进行进一步分析,请运行 linter,例如 eslint。这将自动检测您的问题:

   7:5   error  'iMinimum' is not defined                       no-undef
   8:17  error  'iMinimum' is not defined                       no-undef
  10:28  error  'iMinimum' is not defined                       no-undef
  11:14  error  'iMininum' is not defined                       no-undef
  12:45  error  'iMinimum' is not defined                       no-undef
  15:20  error  'iMinimum' is not defined                       no-undef

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2017-01-16
    • 2018-03-01
    • 2014-06-28
    相关资源
    最近更新 更多