#javascript #function #object #p5.js
#javascript #функция #объект #p5.js
Вопрос:
Это результат, который он возвращает, даже если параметры для проверки очень понятны. Согласно описанию, виновным лицом должна быть Яунита Мирл. Пожалуйста, помогите мне определить, в чем проблема, потому что я не могу понять, что не так с моим кодом:
Вот инструкции:
Officer: 3357927
CaseNum: 701-1-60140847-3357927
Case 701 - Credible cat thief - stage 2
Kid they need you down at the precinct again.
This time it's a sneaky cat thief who has been absconding with the neighbourhoods felines for some time.
Luckily old Mrs Olivetti caught a glimpse of them as they disappeared over her back fence.
We’ve a bunch of likely characters lined-up but we need your brains to solve the mystery.
Please create a function that takes a suspect object as parameter from the data structure below.
Your function should return a boolean value indicating whether or not they match the witness statement.
You should use conditional statements to compare the suspect's properties to the statement.
It should only return "true" if the suspect matches the description in full.
The function is already being called in draw() but it is your job to implement it.
There are many possible ways of carrying out your duties,
but you should complete this task using ONLY the following
commands:
- function testProperties(suspectObj){}
- if()
Witness statement:
It all started when I was exiting the store. That's when I noticed them. I'm pretty sure they were above the age of 48. They had thin blond hair. Their expression seemed menacing. It's so hard to remember right now. The person I saw was male. They wore red glasses. They were quite big, they probably weigh more than 52 Kg. I'm not quite sure. That's all I can remember about them.
Вот код:
var suspectList = [
{
"name": "JENIFFER GOODBURY",
"gender": "female",
"expression": "blank",
"hair": "thick black",
"weight": 64,
"age": 62
},
{
"name": "JAUNITA MYRLE",
"gender": "male",
"expression": "menacing",
"hair": "thin blond",
"weight": 62,
"age": 58
},
{
"name": "TAMICA DURANTS",
"gender": "female",
"expression": "sad",
"hair": "no",
"weight": 100,
"age": 43
},
{
"name": "LESLEY PORTOS",
"gender": "female",
"expression": "angry",
"hair": "long white",
"weight": 92,
"age": 47
},
{
"name": "JACQUELINE SILVEIRA",
"gender": "male",
"expression": "empty",
"hair": "shaved",
"weight": 70,
"age": 21
}
];
var myFont;
var backgroundImg;
function preload() {
myFont = loadFont('SpecialElite.ttf');
backgroundImg = loadImage("Background.png");
}
function setup()
{
createCanvas(640,480);
textFont(myFont);
}
// Declare your function here
function testProperties(suspectObj)
{
if(suspectList.age > 48 amp;amp; suspectList.hair == "thin blond" amp;amp; suspectList.expression == "menacing" amp;amp; suspectList.gender == "male" amp;amp; suspectList.weight > 52 )
{
return true;
}
return false;
}
function draw()
{
//You don't need to alter this code
image(backgroundImg, 0, 0);
for(let i = 0 ; i < suspectList.length; i ){
if(testProperties(suspectList[i]) == true){
fill(255,0,0);
text(suspectList[i].name " is guilty!", 60, 60 i * 20);
}else{
fill(0,155,0);
text(suspectList[i].name " is not guilty", 60, 60 i * 20 );
}
}
}
Ответ №1:
Так близко! Я думаю, у вас опечатка. Вы, вероятно, имели в виду suspectObj
вместо suspectList
в testProperties
:
function testProperties(suspectObj)
{
if(suspectObj.age > 48 amp;amp; suspectObj.hair == "thin blond" amp;amp; suspectObj.expression == "menacing" amp;amp; suspectObj.gender == "male" amp;amp; suspectObj.weight > 52 )
{
return true;
}
return false;
}
var suspectList = [
{
"name": "JENIFFER GOODBURY",
"gender": "female",
"expression": "blank",
"hair": "thick black",
"weight": 64,
"age": 62
},
{
"name": "JAUNITA MYRLE",
"gender": "male",
"expression": "menacing",
"hair": "thin blond",
"weight": 62,
"age": 58
},
{
"name": "TAMICA DURANTS",
"gender": "female",
"expression": "sad",
"hair": "no",
"weight": 100,
"age": 43
},
{
"name": "LESLEY PORTOS",
"gender": "female",
"expression": "angry",
"hair": "long white",
"weight": 92,
"age": 47
},
{
"name": "JACQUELINE SILVEIRA",
"gender": "male",
"expression": "empty",
"hair": "shaved",
"weight": 70,
"age": 21
}
];
function testProperties(suspectObj)
{
if(suspectObj.age > 48 amp;amp; suspectObj.hair == "thin blond" amp;amp; suspectObj.expression == "menacing" amp;amp; suspectObj.gender == "male" amp;amp; suspectObj.weight > 52 )
{
return true;
}
return false;
}
console.log(suspectList.map( s => { return {name: s.name, test: testProperties(s)} }));
Возможно, вам захочется замедлить и перепроверить как код, так и данные (например, это «Jaunita» или «Juanita», является ли Жаклин мужчиной и т. Д.)
Комментарии:
1. Спасибо! Странно то, что это функция, которую они сказали нам использовать, поэтому я просто скопировал и вставил ее
2. Понял. Лично, если это ваш код или чей-либо другой код, когда вы добавляете новую функцию, я рекомендую приобрести привычку тестировать ее. Передайте ему некоторые хорошие и плохие данные, посмотрите, ведет ли он себя так, как ожидалось, исправьте / улучшите в противном случае, а затем двигайтесь дальше. Причина этого в том, что становится все труднее находить проблемы по мере добавления все новых и новых функций, если вы не убедитесь, что все работает правильно до этого момента. Если приведенный выше ответ был решением вашей проблемы, не стесняйтесь пометить его зеленой галочкой 🙂 Удачи!