[英]ReferenceError: num1 is not defined - JavaScript
在 JavaScript 中運行我的簡單腳本時出現以下錯誤:
num1 is not defined
ReferenceError: num1 is not defined
at Object.twoNumberSum (/tester/program.js:8:2)
at Object.exports.run (/tester/json_wrapper.js:8:26)
at Object.<anonymous> (/tester/main.js:21:22)
at Module._compile (internal/modules/cjs/loader.js:1200:30)
at Object.Module._extensions..js
目標是創建一個簡單的 function(未針對時間復雜度進行優化),它接受兩個參數:整數數組和目標總和。 結果應返回一個數組,其中包含任何兩個不同的 integer 元素,總和為目標總和。
這是我的代碼:
function twoNumberSum(array, targetSum) {
for (let i = 0; i < array.length; i++ ){
let num1 = array[i]
};
for (let j =1; j < array.length; j++){
let num2 = array[j]
};
if (num1 + num2 === targetSum){
console.log([num1, num2]);
}
}
這里的任何指針都將不勝感激,因為我不確定這是否是語法問題,或者我正在做的事情對於 JavaScript 來說不是慣用的。
let
在 scope 塊中定義變量,因此它只存在於它所在的大括號之間。
您的第二個循環需要在第一個循環內。
你的代碼邏輯不正確,請看下面的更新版本
function twoNumberSum(array, targetSum) { let num1 = 0 let num2 = 0 for (let i = 0; i < array.length; i++ ){ num1 = array[i] for (let j =1; j < array.length; j++){ num2 = array[j] if (num1 + num2 === targetSum) { console.log(`num1 is ${num1}, num2 is ${num2}`) return } } } console.log('cannot find num1 & num2') } twoNumberSum([1,2,3,4], 5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.