-3

所以我正在创建一个函数来接受两个参数,

  1. 第一个参数是人名
  2. 第二个是他们已经捐赠了多少。

每个人都被分配到一个数组中,具体取决于他们期望捐赠多少。变量中的人

  • a 预计捐赠6个,
  • b 应该捐出 5 和
  • c 捐赠 4。

我希望该函数返回个人应该进行多少捐款,但问题是:无论我在控制台日志中输入什么名称,它始终假定此人来自 var a。我在这里错过了什么吗?

function findDonationRequirement(name, num){

var a = ["shad0vvfax","DarthPolekat","TheSchwartz",
"Johnnie SR91","Brodie", "HolyPaladin", "Kraven", "Dan Solo",
"Khorathian812", "KingWilliam"];

var b = ["Infantry0223","Ru Baruba Maral","Gray JediTim", "Moof Milker",
"Andain", "Cori Starfire", "Nassyy", "Roylas Trebla", "DarthPapirrin",
"MaximusGiganticus", "Wardai", "George3PO", "Revan2017", "Ravishing Dirk",
"dowi", "dogamidstwind", "SpinelessAce", "Devilscut88", "Dagez",
"The Buckster", "ddpf", "WoollyLemurToes", "Emeralthys Phantom  2060095",
"Lightnara1", "JoLy NYC",   "Ccube19", "Anectet Heat", "BigBadBoneDaddy",
"Grizzy", "Zanzibar", "Jesse", "BhMojo", "Kuu Raama", "Jay Fury", "N8Dog",
"Whiskytangofoxtrot"];

var c = ["KingofG0nd0r", "Chrome Cobra", "Bad Rongo", "TK421"];

if (a.hasOwnProperty(name)) {return 6 - num}

else if (b.hasOwnProperty(name)) {return 5 - num}

else if (c.hasOwnProperty(name)) {return 4 - num}

else "Not on list";}

console.log(findDonationRequirement("KingofG0nd0r", 3));
4

2 回答 2

1

而不是a.hasOwnProperty(name)使用a.indexOf(name) > 0

hasOwnProperty是一个 Object 方法,用于查找具有名称的属性name

indexOf是一种 Array 方法,用于在 Array 中查找字面量或对象的位置。找不到时返回-1。因此,使用它的值来确定它是否存在于a数组中。

更多关于indexOf这里https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

于 2018-01-08T16:14:42.387 回答
0

你应该使用 indexOf()

function findDonationRequirement(name, num) {

  var a = ["shad0vvfax", "DarthPolekat", "TheSchwartz",
    "Johnnie SR91", "Brodie", "HolyPaladin", "Kraven", "Dan Solo",
    "Khorathian812", "KingWilliam"
  ];

  var b = ["Infantry0223", "Ru Baruba Maral", "Gray JediTim", "Moof Milker",
    "Andain", "Cori Starfire", "Nassyy", "Roylas Trebla", "DarthPapirrin",
    "MaximusGiganticus", "Wardai", "George3PO", "Revan2017", "Ravishing Dirk",
    "dowi", "dogamidstwind", "SpinelessAce", "Devilscut88", "Dagez",
    "The Buckster", "ddpf", "WoollyLemurToes", "Emeralthys Phantom  2060095",
    "Lightnara1", "JoLy NYC", "Ccube19", "Anectet Heat", "BigBadBoneDaddy",
    "Grizzy", "Zanzibar", "Jesse", "BhMojo", "Kuu Raama", "Jay Fury", "N8Dog",
    "Whiskytangofoxtrot"
  ];

  var c = ["KingofG0nd0r", "Chrome Cobra", "Bad Rongo", "TK421"];

  if (a.indexOf(name)>-1) {
    return 6 - num
  } else if (b.indexOf(name)>-1) {
    return 5 - num
  } else if (c.indexOf(name)>-1) {
    return 4 - num
  } else {
    return "Not on list";
  }
}

console.log(findDonationRequirement("Ccube19", 3));
console.log(findDonationRequirement("Chrome bra", 3));

于 2018-01-08T16:16:23.930 回答