简体   繁体   English

如何使函数接受参数作为JavaScript中的字符串

[英]how to get function to accepts argument as a string in javascript

Think this is a simple question but just can' get my head around it; 认为这是一个简单的问题,但是我无法解决这个问题。

So have these: 还有这些:

var students = ["Joseph", "Susan", "William", "Elizabeth"]

var scores = [ [80, 70, 70, 100], [85, 80, 90, 90], [75, 70, 80, 75], [100, 90, 95, 85] ]

var gradebook = {
Joseph: {
   testScores: scores[0]
},
Susan: {
    testScores: scores[1]
 },
William: {
   testScores: scores[2]
},
Elizabeth: {
   testScores: scores[3]
},
addScore: function(name, score) {
    gradebook[name]["testScores"].push(score);
 },
getAverage: function(name) {
    average(gradebook[name]["testScores"]);
  }
};

var average = function(array) {
  return array.reduce(function(a, b) { return a + b }) / array.length;
};

Have 2 arrays, and gradebook object, want to call gradebook.getAverage("Joseph") and return the average. 有2个数组和gradebook对象,要调用gradebook.getAverage(“ Joseph”)并返回平均值。 but this line average(gradebook[name]["testScores"]); 但是这条线的average(gradebook[name]["testScores"]); in getAverage function I don't think is working. 在getAverage函数中,我认为不起作用。

When I put the code into node terminal and then do gradebook.getAverage("Joseph"); 当我将代码放入节点终端,然后执行gradebook.getAverage("Joseph"); i get undefined. 我不确定。

If I do average(gradebook["Joseph"]["testScores"] in the terminal I get the answer I want. 如果我在终端中执行了average(gradebook["Joseph"]["testScores"] ,我会得到想要的答案。

Hopefully this makes sense! 希望这是有道理的! thanks 谢谢

The reason you are getting undefined from the function call is that they are not returning any value. 您从函数调用中获得undefined的原因是它们没有返回任何值。 Change it to this: 更改为此:

addScore: function(name, score) {
    return gradebook[name]["testScores"].push(score);
 },
getAverage: function(name) {
    return average(gradebook[name]["testScores"]);
  }
};

You need to return the value from the getAverage method: 您需要从getAverage方法返回值:

getAverage: function(name) {
  return average(gradebook[name]["testScores"]);
}

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

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