gpt4 book ai didi

javascript - 我需要获取数组中值的中位数,但我卡住了

转载 作者:行者123 更新时间:2023-12-03 01:51:00 25 4
gpt4 key购买 nike

我正在尝试做这样的事情,但我尝试了多少次都无法正确。我已经尝试了很多方法,目前我已经让它显示项目的总和,但它会跳过每个嵌套数组开头的名称。

           00-08 08-16 16-24 medel
Malmö 12 16 9 12.3
Mariestad 13 15 10 12.7
Stockholm 13 15 13 13.7
Upphärad 14 16 15 15
Göteborg 13 14 12 13


var tempen = [
["", "00-08", "08-16", "16-24"],
["Malmö", 12, 16, 9],
["Mariestad", 13, 15, 10],
["Stockholm", 13, 15, 13],
["Upphärad", 14, 16, 15],
["Göteborg", 13, 14, 12]
];
var newArray = tempen.slice();
tempen[0].push("medel");

function sum_value(prev_value, next_value, ) {
return ( prev_value + next_value);
};

for (var i = 1; i < newArray.length; i++) {
newArray[i].shift();
var sum = newArray[i].reduce(sum_value);
newArray[i].push(sum);
}

function printit() {
var varMyinnerHTML = "<table>";
for (var i = 0; i < tempen.length; i++) {
varMyinnerHTML += "<tr>";
for (var j = 0; j < tempen[i].length; j++) {
varMyinnerHTML += "<td>" + tempen[i][j] + "</td>";
}
varMyinnerHTML += "</tr>";
}
document.getElementById("kontainer").innerHTML = varMyinnerHTML;
}

任何帮助都会很棒,我真的很不擅长:(

最佳答案

你就快到了!这是您的代码,只需进行最少的修改即可正常工作。评论中描述了这些修复。

主要修复:

  • but it skips the name in the beginning of every nested array

    计算总和时,必须删除地名 string确保你不会得到 NaN 。但是,您通过使用 shift 来做到这一点,这将其从您仍需要渲染表格的原始数组中删除。要创建仅包含数字的新数组,可以使用 slice 。这不会改变原始数组,因此您以后仍然可以访问地名。

  • i have got it to show the sum of the items

    您只是按 sum ,但忘记除以值的数量!

  • 您忘记关闭<table>标签

var tempen = [
["", "00-08", "08-16", "16-24"],
["Malmö", 12, 16, 9],
["Mariestad", 13, 15, 10],
["Stockholm", 13, 15, 13],
["Upphärad", 14, 16, 15],
["Göteborg", 13, 14, 12]
];

// We don't need a new array
tempen[0].push("medel");

function sum_value(prev_value, next_value) {
return (prev_value + next_value);
};


for (var i = 1; i < tempen.length; i++) {

// Don't delete the place names from the orginal!
// newArray[i].shift();

// Only skip the place name for the sum
var numbers = tempen[i].slice(1);

var sum = numbers.reduce(sum_value);

// Here, we compute the average by dividing
// sum by length:
var avg = sum / numbers.length;

// Push the average, not the sum:
tempen[i].push(avg);
}


function printit() {
// Add a body
var varMyinnerHTML = "<table><tbody>";

for (var i = 0; i < tempen.length; i++) {

varMyinnerHTML += "<tr>";
for (var j = 0; j < tempen[i].length; j++) {
varMyinnerHTML += "<td>" + tempen[i][j] + "</td>";
}
varMyinnerHTML += "</tr>";
}

// Close the body and table
varMyinnerHTML += "</tbody></table>"

document.getElementById("kontainer").innerHTML = varMyinnerHTML;
}

// Run the code
printit();
<div id="kontainer"></div>

关于javascript - 我需要获取数组中值的中位数,但我卡住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50413259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com