Console.log shows each item in the array on a separate line


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-XEDZA/0/6?curriculum_id=506324b3a7dffd00020bf661


Hello! Stephanie here.

My code passes the objective, and I receive no error messages. The output from the console.log at the end shows exactly what it is supposed to (even the funny places where the computer finds an "S" that is not part of my name). HOWEVER! The output is showing the hits array with each item on a separate row instead of placing the text inline. This oddity goes away when I delete the other instances of the capital "S" in my original text. What is causing this oddity??

Instead of the beautiful inline version from 1. What You'll Be Building:

[ 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c' ]

I see (truncated version so the length of the page doesn't drive you nuts):

[ 'S',
't',
'e',
'p',
'h',
'a',
'n',
'i',
'e',
]


/*jshint multistr:true */

var text = "Hello, my name is Stephanie. / I have been learning coding / for one week and one day. / First, I started with HTML and CSS. / Now, I, Stephanie, am learning Javascript. / I have learned JS before, / but I am relearning / because I want to combine it / with HTML!";
var myName = "Stephanie";
var hits = [];

for (var i=0; i<text.length; i++) {
    if (text[i]==="S") {
        for (var j=i; j<(i+myName.length); j++) {
            hits.push(text[j])
        }
    }
}

if (hits.length===0) {
    console.log("Your name wasn't found!")
} else {
    console.log(hits)
}


#2

@sjeaton12
The problem with this Search Text for Your Name construct
is that it will blindly collect characters if it find the 1st-character-of-your-name.

If you want to change that behaviour
you will have to extend your 2nd FOR-loop

into

        //Begin extended 2nd FOR-loop
        collected="";
        for (var j=i; j<(i+myName.length); j++) {
            //hits.push(text[j])
            collected += text[j];
        }
        if (collected === myName) {
            hits.push(collected);
        }
        //End extended 2nd FOR-loop

==================================

Concerning the =display= of the Array using the console.log() Method
that is how the Interpreter will handle the display as of a certain-Array-length....


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.