如何将传递给函数的参数存储在数组中

How can I store the arguments passed to a function in an array?

本文关键字:存储 参数 数组 函数      更新时间:2023-09-26

我正在尝试解决以下问题,但无法将用户传递给函数的值存储在数组中。以下是问题描述:在这个kata中,我们将帮助Vicky记录她正在学习的单词。

编写一个函数learnWord(word),它是机器人对象的一种方法。函数应该报告该单词现在是否已存储,或者她是否已经知道该单词。

示例:

var vicky = new Robot();
vicky.learnWord('hello') -> 'Thank you for teaching me hello'
vicky.learnWord('abc') -> 'Thank you for teaching me abc'
vicky.learnWord('hello') -> 'I already know the word hello'
vicky.learnWord('wow!') -> 'I do not understand the input'

这是我的代码:

function Robot() {
}
Robot.prototype.learnWord = function(word) 
{
  var res;
  var ans=[];
  if(/^[a-zA-Z- ]*$/.test(word) === true)
  {
      if(ans.indexOf(word)===-1)
      {
          ans.push(word);
          res = 'Thank you for teaching me '.concat(word);
          return res;
      }
      else
      {
          res = 'I already know the word '.concat(word);
          return res;
      }
  }
  else
  {
      res='I do not understand the input';
      return res;
  }
}
var vicky = new Robot();

我希望函数应该将已经传递的参数保存在内存中。

您必须放置"answers",并用"this.ans"替换对"answers的调用。

function Robot() {
   this.ans = []; 
}
Robot.prototype.learnWord = function(word) 
{
  var res;
  if(/^[a-zA-Z- ]*$/.test(word) === true)
  {
      if(this.ans.indexOf(word)===-1)
      {
          this.ans.push(word);
          res = 'Thank you for teaching me '.concat(word);
          return res;
      }
      else
      {
          res = 'I already know the word '.concat(word);
          return res;
      }
  }
  else
  {
      res='I do not understand the input';
      return res;
  }
}

每次你做一个新的机器人();它将有自己的"answers"变量,在原型中,你可以访问你正在使用的机器人的"answers"成员。

如果使用ECMASCRIPT 2015编译器,可以尝试使用(…)rest参数。它们是一组恰当的论据。否则,请使用关键字"arguments",它是一个类似数组的对象。它没有一个合适数组的所有方法,你可以通过它进行循环和.length。它存储传递到函数中的所有"额外"参数,例如那些没有命名参数的参数