簡體   English   中英

為什么我不斷收到錯誤 s 未定義?

[英]Why do I keep getting the error s is not defined?

我正在處理一個家庭作業問題,它不斷返回相同的錯誤。 這是問題寫一個名為“json_average”的function,它采用JSON格式的字符串作為參數,格式為對象數組,其中每個ZA8CFDE6331BD59EB2AC96F8911C4B66F8911C4B66F8911C4B66F8911C4B66F66Z每個鍵映射到一個浮點數。 此 function 應返回數組中所有對象的平均“速度”作為 JSON 字符串,格式為 {"velocity": }

我嘗試使用 let s = 0 和 var = 0 進行切換,無論哪種方式它仍然無法正常工作。 這是我嘗試過的代碼。

function json_average(x) {
    let data = JSON.parse(x);
    var s = 0 ;
    var n = 0; 
    var a;
    for (let i of data) {
        a = i["velocity"];
        s = s + a ;
        n = n + 1 ;
    }
    let d = {"velocity" : (s/n)};
    return(JSON.stringify(d));
}

當我提交代碼時,這就是它返回的內容。

`error on input ['[{"mass": 3.55, "density": 380.72, "velocity": 33.11, "temperature": 46.8}, {"mass": 91.37, "density": 572.04, "velocity": 64.43, "temperature": -0.13}, {"mass": 40.4, "density": 124.52, "velocity": 52.8, "temperature": 38.81}, {"mass": 68.92, "density": 326.77, "velocity": 31.64, "temperature": 43.71}, {"mass": 3.22, "density": 419.85, "velocity": 70.64, "temperature": 23.58}]']:` 
ReferenceError: s is not defined

您在未初始化時嘗試使用 s 。 更新了 function,希望對您有所幫助。

 function json_average(x) { let data = JSON.parse(x); var s = 0; var n = 0; for (let i of data) { let a = i["velocity"]; s = s + a; n = n + 1; } let d = {"velocity": (s/n)}; return(JSON.stringify(d)); }

您正在循環內重新定義已聲明的變量以具有塊 scope(在循環中)。 在塊內用 let 聲明的變量在塊 scope 之外是不可訪問的。 此外,如果您想在 te 循環中給出 s 和這些其他變量塊 scope,您將無法在循環外獲得其值以計算速度。 見 js 小提琴。

 function json_average(x) { let data = JSON.parse(x); var s = 0; var n = 0; for (i in data) { a = data[i]["velocity"]; s = s + a; n = n + 1; } let d = {"velocity": (s/n)}; return(JSON.stringify(d)); } var result = json_average('[{"mass": 3.55, "density": 380.72, "velocity": 33.11, "temperature": 46.8}, {"mass": 91.37, "density": 572.04, "velocity": 64.43, "temperature": -0.13}, {"mass": 40.4, "density": 124.52, "velocity": 52.8, "temperature": 38.81}, {"mass": 68.92, "density": 326.77, "velocity": 31.64, "temperature": 43.71}, {"mass": 3.22, "density": 419.85, "velocity": 70.64, "temperature": 23.58}]'); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM