简体   繁体   English

根据迭代选择字符串

[英]Select String Based on Iteration

I've been trying to practice my Javascript using CodeWars and I'm still in the beginner phase of learning. 我一直在尝试使用CodeWars练习Javascript,但仍处于学习的初级阶段。 I've gotten stuck on this one question and I am hoping someone can explain to me in the most simplest way how to iterate (I believe that's what it's called) through numerous strings based on a number input. 我一直陷在这个问题上,希望有人能以最简单的方式向我解释如何基于数字输入通过多个字符串进行迭代(我相信这就是所谓的)。

Here is the question: 这是问题:

You pick a petal off a flower saying each of the following phrases each time a petal was torn: 您每次从花瓣上摘下花瓣时都会说出以下每个短语:

I love you 我爱你

a little 一点

a lot 很多

passionately 热情

madly 发狂

not at all 一点也不

Your goal in this kata is to determine which phrase you would say for a flower of a given number of petals, where nb_petals > 0 . 您在此kata中的目标是确定要为给定数量的花瓣的花朵说哪个短语,其中nb_petals > 0

So far I have this: 到目前为止,我有这个:

function howMuchILoveYou(nbPetals) {

var petalSaying = ["I love you", "A little", "A lot", "Passionately", 
"Madly", "Not at all"];

for(var petals = 0; nbPetals > 0; nbPetals--);
}

And I'm not sure where to go after this to get it to print out the string necessary based on the number input for nbPetals . 而且我不确定此后要去哪里才能根据nbPetals输入的数字来打印出必要的字符串。

Also, if the number input is 7 for example, it would output I love you . 另外,例如,如果输入的数字是7 ,它将输出I love you

Thanks in advance for any help. 在此先感谢您的帮助。

You don't need to do iteration, just access the given array element by index. 您不需要进行迭代,只需按索引访问给定的数组元素。 If the number is more than the number of elements, use modulus to wrap around. 如果数量大于元素数量,请使用模数进行环绕。

function howMuchILoveYou(nbPetals) {
    var petalSaying = ["I love you", "A little", "A lot", "Passionately", "Madly", "Not at all"];
    var index = (nbPetals - 1) % petalSaying.length;
    return petalSaying[index];
}

nbPetals - 1 adjusts for the fact that array indexes start at 0 , but nbPetals starts at 1 . nbPetals - 1针对数组索引从0开始但nbPetals1开始这一事实进行调整。

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

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