简体   繁体   中英

Looping Through An Array, Putting Each Index On A New Line, And Displaying End Result In An Alert

I am attempting to loop through a dynamic length array, all the while taking the value of each index object and putting it on a new line, with the end "goal", I guess, of displaying the end result in an alert. Really the alert part is just to make sure it is working correctly, but still. I also want to sort the values in ascending alphabetical order in the end result. I plan on sorting first, then loop through, as I assumed this would be easier.

Here is my code currently:

            var mainArr = [];
            var temp = "";
            do {
                temp = prompt("Enter Something... blah blah blah\n\nOr Enter The Number Zero When You Are Done");
                if (temp == 0) {
                    break;
                } else {
                    mainArr.push(temp);
                }
            } while (1);
            mainArr.sort()
            arrLen = mainArr.length
            for (var i = 0; i < arrLen; i++) {
                mainArr[i] = mainArr[i] + "<br />";
                return mainArr
            }
            alert(mainArr);

Currently nothing happens when I enter values into the prompt and finish by entering 0. Meaning when I enter 0, there is no alert. So I know I am missing something here or I am coding something wrong, though I am still fairly new at JS, so I am not sure what is going on here.

Any help would be greatly appreciated. Also if this is a duplicate, please let me know and point me in the right direction. I Googled about a dozen different things to try and find something, but I didn't find anything that quite matched what I am looking for.

You are returning from the loop making alert statement unreachable. You could simply use mainArr.join('\\n') instead

 var mainArr = []; var temp = ""; do { temp = prompt("Enter Something... blah blah blah\\n\\nOr Enter The Number Zero When You Are Done"); if (temp == 0) { break; } else { mainArr.push(temp); } } while (1); mainArr.sort() alert(mainArr.join('\\n')); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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