繁体   English   中英

如何从数组中显示与另一个数组的值相关的值,javascript

[英]How to show a value from array that relates to the value of another array, javascript

我试图用与该名称相关的分数来显示该名称。 因此,如果最高分是98,我希望Joels名字出现在显示屏上,这里的名字说的是。

var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var average;
var total = 0;
var highestScore = 0;

var $ = function (id) { return document.getElementById(id); };

var displayResults = function () {
    for (var i = 0; i < scores.length; i++) {
        total = total + scores[i];       //both are numbers so adds
        if (scores[i] > highestScore) {
            highestScore = scores[i];
        }          
    }

    //then calculate the average and display
    average = parseInt(total/scores.length);
    document.getElementById("results_header").innerHTML = ("Results");
    document.getElementById("results").innerHTML = ("\nAverage score is " + average + "\nHigh score = Name here with a score of " + highestScore); 
};

window.onload = function () {
    //$("add").onclick = addScore;
    $("display_results").onclick = displayResults;
    //$("display_scores").onclick = displayScores;
};

您具有i值(分数在分数数组中的位置)。 这个i值对应于person数组中的person 使用此i值选择人员。

为了使内容更容易,您可以使用一个对象来将名称(字符串)与得分(整数)相关联,例如:

 var test = {"Ben": 88, "Joel": 98, "Judy": 77, "Anne": 88}

然后,您将需要修改for循环。

这些都是在JavScript中执行的非常基本的操作。 希望这些信息对您有所帮助。

我在下面提供了此答案中使用的技术的详细说明。 所有代码片段都可以在您的浏览器中运行。 点击下面的运行代码段以查看结果。

 // input data var names = ["Ben", "Joel", "Judy", "Anne"] var scores = [88, 98, 77, 88] // this is a common way to sum the numbers in an array var total = scores.reduce(function(x,y) { return x + y }, 0) // average = sum of scores / number of scores var average = total / scores.length // use Math.max to find the highest score var highScore = Math.max.apply(null, scores) // get the name matching the highest score var highScoreName = names[scores.indexOf(highScore)] // output the information to the console // alternative: use innerHTML or something else to print to the DOM console.log("total: %d", total) console.log("average: %d", average) console.log("highest score: %s had %d", highScoreName, highScore) 


对一个数字数组求和:

您可以使用for循环或forEach但这是针对穴居人的。

 var scores = [88, 98, 77, 88] var total = 0 for (var i = 0; i < scores.length; i++) { total = total + scores[i] } console.log("total scores: %d", total) // 351 

一旦您了解了Array.prototype.reduce等高阶函数,您将永远不会回到过去的当务之急

 var scores = [88, 98, 77, 88] var total = scores.reduce(function(sum, score) { return sum + score }, 0) console.log("total scores: %d", total) // 351 

无需过多地困扰您,我们的scores数组中的每个元素都会调用一次简化函数function(sum, score) { sum + score } 该函数的返回值将在下次调用时用作sum

iteration     sum       score      return
-----------------------------------------------------------------
#1            0         88         0 + 88 (88)
#2            88        98         88 + 98 (186)
#3            186       77         186 + 77 (263)
#4            263       88         263 + 88 (351) <-- final value

var total = scores.reduce(function(sum, score) { return sum + score }, 0)
// 351

查找数组的最大数量:

同样,我们可以使用像这样的尼安德特人的技巧

 var max var scores = [88, 98, 77, 88] for (var i = 0; i < scores.length; i++) { if (max === undefined) max = scores[i] else if (max < scores[i]) max = scores[i] } console.log("max score: %d", max) // 98 

但是我们比这聪明得多,对吗? 我们可以再次访问Array.prototype.reduce ,但这一次有一个更好的方法。

Math.max将告诉我们提供的最大输入量

 var max = Math.max(1, 5, 9, 3, 10, 6) console.log('max: %d', max) // 10 

如果我们可以只编写Math.max(scores)来获取highScore变量的值,那将是很好的highScore ,但是Math.max仅适用于数字,而不适用于数组。 为了解决这个问题,我们可以使用Function.prototype.apply将函数应用于参数数组。 这非常适合我们的需求

 var scores = [88, 98, 77, 88] // this is the same as writing Math.max(88, 98, 77, 88) // but .apply allows us to keep the score values in an array var max = Math.max.apply(null, scores) console.log("max score: %d", max) // 98 


将高分链接到相应的名称:

获得highScore值后,我们必须找到与该分数匹配的人的名字。 我们要做的highScorescores数组中对highScore值的索引进行highScore ,然后从具有相同索引的names数组中查找该值。

由于highScore值是scores数组中的已知值,因此可以使用Array.prototype.indexOf并确保将返回有效索引。

 var scores = [88, 98, 77, 88] var highScore = Math.max.apply(null, scores) var highScoreIndex = scores.indexOf(highScore) console.log("highScore: %d, highScoreIndex: %d", highScore, highScoreIndex) // highScore: 98, highScoreIndex: 1 

我们看到highScoreIndex: 1因为数组索引从0开始并向上计数。 数组索引1实际上是指数组中的第二个元素。

所以现在我们要做的就是使用索引1查找名称以获取相应的名称值

 var names = ["Ben", "Joel", "Judy", "Anne"] var scores = [88, 98, 77, 88] var highScore = Math.max.apply(null, scores) var highScoreIndex = scores.indexOf(highScore) var highScoreName = names[highScoreIndex] console.log("high score of %d by %s", highScore, highScoreName) // high score of 98 by Joel 

由于namesscores数组具有相同的.length ,因此可以使用与在scores选择项目相同的i变量在names数组中选择项目。

声明name变量

var name = "";

设置name变量

if (scores[i] > highestScore) {
  highestScore = scores[i];
  name = names[i];
}

显示name变量

document.getElementById("results")
.innerHTML = "\nAverage score  is " 
          + average 
          + "\nHigh score = " 
          + name 
          + " here with a score of " 
          + highestScore;

您可以存储索引而不是最高分,然后使用它来获取名称。 我已更改了您的代码以支持它,并在更改的位置添加了注释“更改”,

 var names = ["Ben", "Joel", "Judy", "Anne"];
    var scores = [88, 98, 77, 88];
    var average;
    var total = 0;
    var highScoreIndex = 0;// Changes

    var $ = function (id) { return document.getElementById(id); };

    var displayResults = function () {
        for (var i = 0; i < scores.length; i++) {
                total = total + scores[i];       //both are numbers so adds
                    if (scores[i] > highestScore) {
                highestScoreIndex = i; // Changes
            }

           }

    //then calculate the average and display
            average = parseInt(total/scores.length);
            document.getElementById("results_header").innerHTML =   
     ("Results");
            document.getElementById("results").innerHTML = ("\nAverage score  
          is " + average + "\nHigh score = " + names[highestScoreIndex] + " with a score of " +    
        scores[highestScoreIndex]); //Changes


    };

    window.onload = function () {
        //$("add").onclick = addScore;
        $("display_results").onclick = displayResults;
        //$("display_scores").onclick = displayScores;
    };
else {
names[names.length] = nameInput;

转换为数字

scoreInput = Number(分数输入);

scores[scores.length] = scoreInput;

//然后计算平均分数和最高分数

var displayResults = function () {   

重设总计

总数= 0;

    for (var i = 0; i < scores.length; i++) {
            total = total + scores[i];      
                if (scores[i] > highestScore) {
            highestScore = scores[i];
            name = names[i];

试试吧 :

 <html> <head> <style> </style> </head> <body> <p id="results"></p> <button id="display_results">Show</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> var names = ["Ben", "Joel", "Judy", "Anne"]; var scores = [88, 98, 77, 88]; var average; var total = 0; var highestScore = 0; var hightName = ""; function displayResults () { for (var i = 0; i < scores.length; i++) { total = total + scores[i]; //both are numbers so adds if (scores[i] > highestScore) { highestScore = scores[i]; hightName = names[i]; } } //then calculate the average and display average = parseInt(total/scores.length); document.getElementById("results").innerHTML = ("\\nAverage score is " + average + "\\n High score = " + hightName + " with a score of " + highestScore); }; //$("add").onclick = addScore; $(document).ready(function(){ $("#display_results").click(function(){ displayResults(); }) }) </script> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM