坚持我的游戏的JavaScript功能

时间:2018-01-08 16:11:19

标签: javascript arrays function hasownproperty

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

  1. 第一个参数是人物的姓名
  2. 第二个是他们已经捐赠了多少钱。
  3. 根据预计捐赠的数量,将每个人分配到一个阵列。变量中的人

    • 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));
    

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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));