So. Started arrays. Yeah went as well as the loops did. And as a result, I need help.
/*jshint multistr:true */
var text = "Yo yo yo, what's / good fam. My name is / Caleb, my dude.";
var myName = "Caleb"
var hits = []
for(var i = 0; i >= text.length; i++){
if(text[i] === 'C') {
}
for(var j = i; i <= i + myName.length; i++){
}
}
That is the exact code that I have. Now, What it needs to do is search for my name within the confines of the text string. Only problem is that its saying that "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." This is a CodeAcademy project. I'm just not understanding. If someone could help me with this, I would really appreciate it.
Thanks!
First of all make sure you have all the semicolons right. Also, add some action in case the loop gets a result!
Also, i don't think you have defined var j, did you?
Finally - if it's asking u to push some values into hits array, then use this push method:
hits.push();
To help u i'd need deeper understanding of the task itself. what did u have to do, what were u starting with?
Edit:
var myName = "Caleb"; // define myName before text so it can be used in text
var text = "Yo yo yo, what's / good fam. My name is / "+myName+", my dude."; // define text and use myName variable between two strings, connected with +
var hits = []; // define hits array
for(var i = 0; i < text.length; i++) { //start loop, make sure second parameter is not infinite or it would crash your browser
if(text[i] === 'C') { // if found i that corresponds with 'C'
var letterLocation = i; // set variable letterLocation with value of 'C' position
hits.push(i); // add the location number to hits array with .push method
};
};
console.log(hits); // display hits array in console
Here's some working code for you, just follow the task and change whatever is necessary - hope it helps.
Generally - i changed the order of variables, so that u can use myName in text, also made the for loop print out the position of letter C and push this value into the hits array. Is that what u meant?
Related
I am new to js and hope this is not too trivial, but I am unable to find any help on the net.
I wish to output to console.log and prevent moving to a new line, so the next time the output will be appended to the same line. ie,
"use strict";
for (let i = 0; i<=9;i++){
console.log(i); // here i would like to freeze the output so the result is 0123456789 on one line, rather than those digits in a column.
}
I have seen fixes involving assigning the outputs to a string and printing in 1 hit, but that seems incredibly crude. Even in Fortran 4 as I recall in the '70s, you could prevent moving to a new line before printing again, so I think I am missing something fundamental. Also I cannot find any general help on formatting numerical output in javascript. Can someone point me in the right direction?
Thanks
Unfortunately, the console.log() method will only write out a string to a single line and doesn't support the appending behavior you are looking for.
As you detailed in your original post, you could accomplish writing the final result out through the use of a variable (i.e. displaying the final concatenated string), but not continually appending to the same line within the console itself as the loop is being iterated over.
Alternative Grouping Option
The concept of grouping entries is supported, which is obviously very different than your original ask, but it may be worth considering as mentioned in the documentation for console.group() and might look something like this:
var rollingConcatenation = '';
console.group("Looping Group Example");
for (let i = 0; i<=9;i++){
rollingConcatenation += i;
console.log(rollingConcatenation);
}
console.groupEnd();
This can give your console the following appearance, which can help with readability (depending on your use cases):
Do It Yourself Implementation
Another option might be to store your current console value within a variable and at clear it and rewrite the updated values out. Depending on your very specific use cases, you could achieve the behavior you are looking for using something like this crude implementation:
// Define a custom console
var customConsole = {
// Store a reference to your backing value
tempValue: '',
// Always write out the most recent value
log: function(msg) {
this.tempValue += msg;
console.clear();
console.log(this.tempValue);
},
// A clear method to clear the backing console
clear: function() {
this.tempValue = '';
console.clear();
}
}
for (var i = 0; i < 10; i++) {
// Use your custom console instead of the normal one
customConsole.log(i);
}
Take a new variable outside the loop and then prepare that string inside the loop and then you can console.log() outside the loop.
var str = '';
for (let i = 0; i <= 9; i++) {
str += i;
}
console.log(str);
I want my code to check if a variable has increased. For example, I have a function that looks for the letter A in a text box, which runs every time a key is pressed. Then it counts the number of A's it has found. Then I want to alert me everytime a new A is written. I thought I could do this easily by just checking if the var numberOfA has increased in an if statement, and if it has to alert me, but I can't figure it out. I have tried using ++ and =/== in my if statement, but it alerts me every single time a letter is typed, instead of only everytime an A has been typed. All help is appreciated, I'm pretty new at this.
function checkForA(){
var sentence = document.getElementById("userText").value.match(/a/g);
var numberOfA = sentence.length;
if (numberOfA = numberOfA +1) {
alert(" The letter A has been typed ");
}
}
Several problems.
When you write numberOfA = numberOfA + 1, you actually assign a value to numberOfA. Use a === b if you want to test equality.
Also, if you decide to use numberOfA to store the previous count, then you need to compare that with the current sentence.length value.
As a side note: if you are new, then invest time in learning how to use the debugger (e.g. in the browser dev tools). It will save you a lot of time and help you really understand what is happening.
You can not check numberOfA = numberOfA + 1 in your if statement. You can try this -
var numberOfA = 0;
function checkForA(){
var sentence = document.getElementById("userText").value.match(/a/g);
if (sentence.length > numberOfA) {
numberOfA = sentence.length;
alert("The letter A has been typed. In your sentence A has found "+numberOfA+" times.");
}
}
I'm trying to sum variables with sequential names in a field (sum) for a PDF Form, but the code is not working.
New to all things programming, I've read a bit on arrays but only found cases where all the variables are thoroughly declared (written) before the problem. My case is exactly to find a working code that "arrays" sequentially-named variables inside a sum operation.
My variables are named textbox1, textbox2, ..., textbox200 (all of which being varied integer numbers), so I'd very much like to find a way to avoid having to write down 200 var [i]=this.getField("textbox[i]");
and tidy up 200 var lines...
I've tried this:
var x=this.getField ("sum")
x.value = 0;
for(var i = 0; len = 201; i < len; i++) {
x.value += (var [i]=this.getField("textbox[i][1]"));
}
Probably got some logic/language principle all wrong, could someone give me directions please? EDIT: also, considering pdf form js seems to need a .value after any variable, that is probably another missing aspect in the code, but I'm not sure where it would be placed. tried altering to (var [i].value=this.getField("textbox[i][1]")), still the sum field shows nothing.
Thanks.
PS. I realize PDF forms can perform sum operations quite easily by selecting the fields to be added, but considering I need it to have more flexibility than only adding the fields (and not willing to click 200 checkboxes out of 500+), I need to use the javascript console for the calculation(I think).
EDIT2: Tried this too, adding the .value where it seemed to make sense.
var x=0;
for(var i=1; i<=200; i++) {
var y=this.getField("textbox"+i)
x.value = x.value + y.value
}
event.value = x.value
Still no response from the sum field box.
Based on the code in EDIT2, the problem is with the "x". You define it as a number, and a number does not have a value property.
Therefore, this should work:
var x = 0 ;
for (var i = 1 ; i <= 200 ; i++) {
x += this.getField("textbox"+i).value*1 ;
}
event.value = x ;
We multiply the field value with 1, in order to force it to a number, something which is necessary to deal with empty fields (an empty field has the value of the empty string, which means that the numbers are not added but concatenated).
I´ll try to be very specific about this topic.
So I have a "for" loop in javascript working just fine. The loop aims to retrieve the URLs of all the files existing in a target folder. The question is, how can I save the retrieved URLs into individual variables?
So, in order to make things easy, I won´t paste the code I´m using, I´ll just create a simple array and run a "for" loop as an example, so you guys can tell me how you would try to save the results into new variables.
So here's the example:
var index;
var arrayElements = ["FirstURL", "SecondURL", "ThirdURL"]
for (index = 0; index < arrayElements.length; index++) {
document.write (arrayElements[index]+"<br/>");
}
So, with that code, I can "print" the different URLs included in the array (I could use console.log of course, but I´m writing in notepad++, so I have to test the code with document.write)
So the question, how can I save each URL into an individual variable?
EDIT:
Ok, so reading the first answers, I think I must clarify some things.
The question is that I need to store the URLs in variables so I can call them later. So it´s not a question about "printing" the URLs.
The function eval()
I know eval is bad
var data = ["a", "b", "c"];
function makeIndvidualVariable(array){
var size;
try{
size = array.length;
for(var i = 0 ; i < size ; ++i){
if( eval(array[i]) != undefined){
eval("var "+array[i]+"="+array[i]+";");
}else{
throw "already exist variable : "+array[i];
}
}
}catch(e){
console.log(e);
}finally{
array = size = i = null;
}
}
makeIndvidualVariable(data);
You can obtain individual variables with window object (if i got you properly).
Use the thing with JS that enables you to declare variables in window scope.
var index;
var arrayElements = ["FirstURL", "SecondURL", "ThirdURL"]
for (index = 0; index < arrayElements.length; index++) {
window['variable'+index] = arrayElements[index];
}
// now variables are available globally (through window object)
document.write(variable0); // prints FirstURL
document.write(variable2); // prints ThirdURL
// etc.
Hope this helps.
Just for the sake of printing the urls stored in array one by one and avoid loops you can use this:
document.write (arrayElements.join("<br/>"));
I was working on counting sort1 problem on hackerrank. I am using JavaScript to solve the problem.
Standard input is providing a number and an array which I was reading like this
var inp = input.split('\n')
var n = parseInt(inp[0]); //Number of elements
var ar = inp[1].split(' ').map(function(item){
return parseInt(item);
}); //Array of numbers.
I was using above code in almost all of my solutions, it always worked.
Then I process the above array ar in for loop which is giving runtime error in one of the test cases(last testcase).
for(var i = 0; i < n; i++) {
var number = ar[i];
//more code
}
But if I don't parse elements of the array using map function but parse them later in for loop, one by one, I don't get any error.
var ar = in[1].split(' '); //Array of numbers in string format
for(var i = 0; i < n; i++) {
var number = parseInt(ar[i]);
//more code
}
Can Anyone explain Why?
in is a keyword, and you are trying to use it as a variable. I'm not sure why it says "Runtime Error", since this is actually a parsing error. Once renamed to something else, I could run the first two paragraphs error-free.
The only problem I remember having on Hackerrank that the .split() method often gave an empty string ("") as the last element of the array. Probably that's why you failed on the last test case.
Make your logic like:
if(arr[i] !== "")
// perform operations
else
break;
Also, you can't use in as a identifier because it is a reserved keyword.