Multiple conditions using for loop - javascript

I'm beginning programming with codecademy and I tried to write a "search for word" program, but I don't know how to write a condition in if using a for loop to check all the letters in a search word, no matter the length.
I know the for loop gives me true or false, but I would like it to generate as many text[j] === myWord[j-i] conditions to my code as there are letters.
Is there something wrong with my syntax or should I use other command that I don't know of?
var text = "Within the field of literary criticism, text also refers to the original information content of a particular piece of writing; that is, the text of a work is that primal symbolic arrangement of letters as originally composed, apart from later alterations, deterioration, commentary, translations, paratext, etc. Therefore, when literary criticism is concerned with the determination of a text, it is concerned with the distinguishing of the original information content from whatever has been added to or subtracted from that content as it appears in a given textual document (that is, a physical representation of text).";
var myWord = "literary";
var hits = [];
for (var i=0; i < text.length; i++) {
if (for (var j=i; j<(i + myWord.length); j++){
text[j]===myWord[j-i]
})
hits.push(text[i])
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
}
else {
console.log(hits);
}

You should move the if condition inside the inner loop like below
for (var i = 0; i < text.length; i++) {
for (var j = i; j < (i + myWord.length); j++){
if(text[j]===myWord[j-i])
hits.push(text[i]);
}
}
}

Related

comparing GUID/UUIDs in javascript

I have a function that is supposed to filter out messages without the same UUID in javascript. However when comparing, nothing is equal, even the ones that clearly are. They are all lowercase on both sides and when you console log they come out looking identical.
Interesting detail that might lead to whats wrong. I cannot use the trim function on first guid without some kind of string conversion first
function filterReceivedMessages()
{
var neededMessages = [];
for(var i=0; i < messages.length; i++)
{
if((messages[i].orginator+"").trim() != client.GetUserUid().trim())
{
neededMessages.push(messages[i]);
}
}
return neededMessages;
}

javascript loop string comparison headache

console.log(previousCompetitors);
console.log(competitors);
if(data.isVisible) {
var moveIndexTo = [];
for(var q=0; q<competitors.length;q++) {
moveIndexTo.push(-1);
}
for(var i = 0; i<competitors.length; i++) {
for(var j = 0; j<previousCompetitors.length; j++) {
console.log(competitors[i].name);
console.log(previousCompetitors[j].name);
if(competitors[i].name === previousCompetitors[j].name) {
moveIndexTo[j]= i;
break;
}
}
}
console.log(moveIndexTo);
}
I'm slowly going insane trying to figure out what is happening here. I have an array of competitor data that updates in order. They are both arrays and I want to track the changes from the previous ordering.
I console.log the data and can see that the data order has been changed yet every single time the moveIndexTo array ends up being [0,1,2,3,4,5] implying that previousCompetitors an Competitors have equal order. How can they be changed between when I console.log them at the top of the code block to when I perform the string comparison?
Competitors and previousCompetitors take roughly the form
[{name:'name1'},{name:'name2'},{name:'name3'},{name:'name4'},{name:'name5'},{name:'name6'}]
with a lot more going on in each object. So If that was previousCompetitors then competitors would be something like
[{name:'name6'},{name:'name2'},{name:'name3'},{name:'name4'},{name:'name5'},{name:'name1'}].
Note the switch of name1 and name6. So I would expect moveIndexTo to be [5,1,2,3,4,0].
Just try this : moveIndexTo[i] = j;
fiddle at : https://jsfiddle.net/c9mbbpjj/

Text based rpg javascript practice project

I was told making a game would be a good way to learn how to use javascript properly so I have started a game in which thus far the player is prompted to create a hero, and then assign attributes to it based on its hero type(magerouge, necromancer, warlock, or shaman) however when I get to the point of assigning attributes it always says the user picked a necromancer no matter what class he actually chose. So in short something is wrong with my function called "defaultAssign". I hope i am posting this question properly, if i am posting incorrectly please let me know so I can try to fix it, this is my first question. Here is my code:
var heroArray = [];
var yourHero ="";
var hero = {
characterType:"",
Damage:0,
Health:0,
Mana:0,
ManaRegenRate:0,
HealthRegenRate:0,
SpecialSkills:[]
};
var mainMenu = function(){
var nameCheck = prompt("What is your Character's Name?").toUpperCase() ;
for( var i = 0;i <= heroArray.length ; i++){
if (nameCheck === heroArray[i]){
alert("We have found your hero change this string later");
runGame(heroArray[i]);
}
else{
alert("You Must Create a Champion");
var heroName = prompt("What Will You Name Your Sorcerer!").toUpperCase;
characterCreator(heroName);
/*use a loop with a regular expression here to check if the name is avalible, if it is countinue, if not
prompt the user for another name
*/
}
/* run "gameSave" for particular hero
Run the main Game function and print to the console:
"Ah yes "+yourHerosNameHere+"," +hisOrHer+" tale echoes far and wide. We last spoke of his journey to"
+insertCurrentCityHere+" where "+heOrShe+" "mostRecentAction"."
*/
}
}
var characterCreator = function(yourHero){
yourHero = Object.create(hero);
yourHero.characterType = prompt("Choose your Character Type:\n"+
"MageRouge\n"+
"Warlock\n"+
"Shaman\n"+
"Necromancer").toUpperCase;
defaultAssign(yourHero.characterType)
}
function defaultAssign(playersType){
for (var j = 0 ; j <= 3 ; j++){
if (playersType === "MAGEROUGE"){
yourHero.Damage=25;
yourHero.Health=50;
yourHero.Mana=15;
yourHero.ManaRegenRate=1;
yourHero.HealthRegenRate=0.4;
yourHero.SpecialSkills=[["pickpocket",],["sneak",],["lockpick",]];
alert("Ahha a powerful Magerouge, choose your skills emphasis wisely,"
+" it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
if(playersType === "WARLOCK"){
yourHero.Damage=50;
yourHero.Health=50;
yourHero.Mana=25;
yourHero.ManaRegenRate=0.6;
yourHero.HealthRegenRate=0.3;
yourHero.SpecialSkills=[["summonDemon",0],["bindDemon",0],["portal",0],["illusion",0]];
alert("Ahha a powerful Warlock, choose your skills emphasis wisely,"
+"it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
if(playersType === "SHAMAN"){
yourHero.Damage=40;
yourHero.Health=50;
yourHero.Mana=30;
yourHero.ManaRegenRate=0;
yourHero.HealthRegenRate=0.6;
yourHero.SpecialSkills=[["weatherControl",0],["heal",0],["astralProjection",0]]
alert("Ahha a powerful Shaman choose your skills emphasis wisely,"
+"it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
else if(playersType === "NECROMANCER") {
yourHero.Damage=60;
yourHero.Health=50;
yourHero.Mana=20;
yourHero.ManaRegenRate=0.8;
yourHero.HealthRegenRate=0.4;
yourHero.SpecialSkills=[["raiseDead",0],["petrify",0],["soulSap",0]];
alert("Ahha a powerful Necromancer choose your skills emphasis wisely,"
+"it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
}
}
/*
create an array of hometowns for the main character to choose from
*/
function skillAssigner(yourHero){
for (var s = 0;s<3;s++){
var p = 0;
while( p < 10 ){
var n = prompt("How many points will you spend on "+yourHero.SpecialSkills[s]+"?");
yourHero.SpecialSkills[s][1] = n;
p +=n;
}
}
}
mainMenu();
Get rid of the else on the line where it checks if the player's type is a Necromancer. It is not necessary.
The for loop is not necessary inside the function defaultAssign (and with its removal, nor are the breaks.)
Finally, toUpperCase is a function so you must invoke it with parentheses, toUpperCase().
Resolving these issues gets your code to work.
You should work on formatting your code (or get an editor that does it for you) to increase its readability-- this will help you find errors.

Javascript stuck at "for" loop

i am newbie learner and i am learning basic javaScript from codecademy.I stuck at "Search Text for Your Name" tutorial 5/7.
here is my question:
your loop should stop when it hits the value of the first iterator (say, i)
plus the length of your myName variable.
here is some informations from to tutorial:
Your second "for" loop
Okay! Last loopy step: add another for loop, this time inside the body of your if statement (between the if's {}s).
This loop will make sure each character of your name gets pushed to the final array. The if statement says: "If we find the first letter of the name, start the second for loop!" This loop says: "I'm going to add characters to the array until I hit the length of the user's name." So if your name is 11 letters long, your loop should add 11 characters to hits if it ever sees the first letter of myName in text.
For your second for loop, keep the following in mind:
First, you'll want to set your second loop's iterator to start at the first one, so it picks up where that one left off. If your first loop starts with
> for(var i = 0; // rest of loop setup
your second should be something like
> for(var j = i; // rest of loop setup Second
think hard about when your loop should stop.
Finally, in the body of your loop, have your program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array. For example,
newArray = [];
newArray.push('hello');
newArray[0]; // equals 'hello'
and here is my code:
multistr:true
var text = "Hey, how are you \
doing? My name is Emily.";
var myName = "Emily";
var hits = [];
for (var i = 0; i > text.length; i++)
{
if (text[i] === 'E')
{
for(var j = i; j > text.length; j++){
};
};
};
ps: i don't want to pass this tutorial without understand it. please help me. teach me.
for (var i = 0; i > text.length; i++) should be
for (var i = 0; i < text.length; i++)
otherwise it won't ever meet the criteria to even start the loop.
Welcome on board! You confused > with <. Your loops won't run because for the first check when i = 0 it certainly does not hold that 0 > text.length, because text.length is at least 0 (there are no strings shorter than the empty string).
You should make a habit of manually going through your loops for the first two steps and then check what happens just before the loop ends.
Here is what I got for my code:
for ( i = 0; i < text.length; i++)
{
if ( text[i] === "E")
{
for( var j = i; j < (myName.length + i ); j++)
{
hits.push(text[j]);
}
}
};
It looks like you were missing the " + i " part in your second for loop. That seems to make sure that the first loop will be included. I tried it without the "+ i" and it does not work.
I tried continuing directly from the second for loop using a "+ j" and that only crashes the browser.

Javascript code help - Wrong return

So I'm working on this script. When I'm done with it, it should be used for making 2-and-2 groups. But anyway; The 'input' array in the start of the script, will get 22 different inputs from my HTML file. As a standard, I gave them the values 1-22. The thing is my two blocks '1st number' and '2nd number' doesn't work very well: they don't return the right numbers. Cause I want every elev[x] to be used once! Not 2 times, not 0 times, once! And the blocks returns like some of them twice and some of them isn't even used. So how can I fix this?
function Calculate(){
var elev = [];
var inputs = document.getElementsByName("txt");
for(i=0; i<inputs.length; i++) {
elev[i] = {
"Value": inputs[i].value,
"Used": false
};
}
function shuffle(elev){
var len = elev.length;
for(i=1; i<len; i++){
j = ~~(Math.random()*(i+1));
var temp = elev[i];
arr[i] = elev[j];
arr[j] = temp;
}
}
for(var v=0; v<1; v++) {
shuffle(elev);
document.write(elev + '<br/>\n');
}}
Yes, I'm still new at programming and I just wanna learn what I can learn.
Problem solved by doing the Fisher-Yates shuffle.
The idea of shuffling an array and iterating over it is correct, however, sorting by a coin-flipping comparator (a common mis-implementation; suggested by the other answer) is not the correct way to shuffle an array; it produces very skewed results and is not even guaranteed to finish.
Unless you're willing to fetch underscore.js (arr = _.shuffle(arr)), It is recommended to use the Fisher-Yates shuffle:
function shuffle(arr){
var len = arr.length;
for(var i=1; i<len; i++){
var j = ~~(Math.random()*(i+1)); // ~~ = cast to integer
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
...
shuffle(elev);
for(var i=0; i<elev.length; i++){
//do something with elev[i]
console.log(elev[i].Value);
}
also, note that object fields should be lowercase, not uppercase (value', not 'Value'). Also, theUsed` field should not be neccessary since you now iterate in order. Also, any chance you could use an array of Values? They seem to be the only field in your objects.
Also, Don't use document.write(). It doesn't work as expected when used after the page load. If you want to append something to the document, you hate jQuery and other frameworks and you don't want to go the long way of creating and composing DOM nodes, document.body.innerHTML += is still better than document.write() (but still consider appending DocumentFragments instead').
demo: http://jsfiddle.net/honnza/2GSDd/1/
You are only getting random numbers once, and then processing them if they haven't already been used.
I would suggest shuffling the array (elev.sort(function() {return Math.random()-0.5})) and then just iterating through the result without further random numbers.

Categories