How to use .push!


#1



Oops, try again. It looks like your second 'for' loop isn't pushing values to the hits array. Make sure it's working properly and that myName's text appears somewhere in the text variable.


var text = "asdfasdfasdfasdfasdflucasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdflucasdfasdfasdfasdfasdfasdflucasdfasdfasdfasdfasdflucasdfasdfasdfasdflucasdfasdfasdfasdflucasasdfasdfasdf"
var myName = "Lucas"
var hits = []

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


#2

push is explained briefly in the lesson, but if you have the time to segue into some quick reading, look up,

Array.prototype.push
Array.prototype.pop
Array.prototype.unshift
Array.prototype.shift

To use it, we 'call the method on the array object'

hits.push()

That's the syntax. .push() is a method of the Array class of JS objects. Of course we have to have something to the cart...

hits.push(text[j]);

Given an array of N elements, after array.push(x), the array will have N + 1 elements, x being the last.

The method as much as appends a new element to the array. That element may be any object.

Your resulting hits array should look like this (but doesn't),

`[ 'L','u','c','a','s', 'L','u','c','a','s', 'L','u','c','a','s', 'L','u','c','a','s', 'L','u','c','a','s', 'L','u','c','a','s']

because none of the instances is capitalized. Proper names are always capitalized.


#3
  1. if (text[i] === 'lucas') always returns false. Should be

if (text[i] === 'l')
// OR
if (text[i] === myName[0])

BUT

var myName = "Lucas"; // begins with uppercase, but var text doesn't contains 'L'
  1. From previous answer:

hits.push(text[j]);

#4

/*jshint multistr:true */
var text = "asdfasdfasdfasdfasdfLucasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfLucasdfasdfasdfasdfasdfasdfLucasdfasdfasdfasdfasdfLucasdfasdfasdfasdfLucasdfasdfasdfasdfLucasasdfasdfasdf"
var myName = "Lucas"
var hits = []

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


#5

Crashes my browser

How do you think why??
Just compare:

var text = "asdfasdfasdfasdfasdfLucasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfLucasdfasdfasdfasdfasdfasdfLucasdfasdfasdfasdfasdfLucasdfasdfasdfasdfLucasdfasdfasdfasdfLucasasdfasdfasdf";
var myName = "Lucas";
var hits = [];

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

#6

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