繁体   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