简体   繁体   English

JavaScript遍历数组

[英]JavaScript looping through array

I'm trying to complete this assignment, I've got the code set up, however, there's a problem. 我正在尝试完成此任务,已经设置了代码,但是有问题。

The assignment : "Create an array with seven string values, initialized to the names of these stars: Polaris, Aldebaran, Deneb, Vega, Altair, Dubhe, and Regulus. Create an array with seven additional string values, initialized to the names of the constellations in which the stars are found: Ursa Minor, Taurus, Cygnus, Lyra, Aquila, Ursa Major, and Leo. Next, create a function that accepts a single string parameter. Within the function, iterate through the first array, searching for the star. When the star is found, return the value contained in that index within the second array. In other words, return the constellation name for that star. Use a prompt to gather the name of the star from the visitor, and then call the function with that input. Don't forget to include code that executes when the star isn't found. Display the result on the screen." 作业 :“使用七个字符串值创建一个数组,将其初始化为以下星星的名称:北极星,Aldebaran,Deneb,Vega,Altair,Dubhe和Regulus。使用七个其他字符串值创建一个数组,并将其初始化为这些星星的名称在其中找到星星的星座:小熊座,金牛座,天鹅座,天琴座,天鹰座,大熊座和狮子座接下来,创建一个接受单个字符串参数的函数,在该函数内,迭代第一个数组,搜索找到星星后,返回第二个数组中该索引中包含的值,换句话说,返回该星星的星座名称,使用提示从访客那里收集星星的名称,然后调用输入的功能。别忘了包含找不到星号时执行的代码。在屏幕上显示结果。”

The code : 代码

var stars  = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var stars2 = ["Ursa Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major", "Leo"];

function processStar(starName){
    for (var i=0; i < stars.length; i++) {
        if(starName == stars[i]){
            return stars2[i];
        } else {
            return "No star found!";
        }
    }
}

var getStar = prompt("Input the star name.");
var result = processStar(getStar);
alert(result);

The problem : 问题

This code works only for the first value in the stars array. 此代码仅适用于stars数组中的第一个值。 Anything other than the first element of that array ("Polaris"), the function returns with false value. 除了该数组的第一个元素(“ Polaris”)之外,该函数均返回false值。

在循环体内,您总是返回一个值,因此循环体将只执行一次。

Your conditional statement is wrong. 您的条件陈述是错误的。 Try this out. 试试看

var stars  = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var stars2 = ["Ursa Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major", "Leo"];

function processStar(starName){  
    for (var i=0; i < stars.length; i++) {
    if(starName == stars[i]){
        return stars2[i];
    } 
}

return "No star found!";

}

var getStar = prompt("Input the star name.");
var result = processStar(getStar);
alert(result);

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

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