I'm doing Udacity javascript studies now and there is one quiz that bothers me. I know how to do it easily in ruby, but this one is killing me.
I need to call function and return "ha" num times and add "!" at the end with the loop.
I tried this but it didn't help. Should be very simple.
function laugh(num) {
for (var x = 0; num; x ++) {
return 'ha';
}
}
console.log(laugh(3));
Actually you don't even need the loop.
const laugh = num => 'ha'.repeat(num) + '!';
console.log(laugh(3));
console.log(laugh(5));
Returning in a loop will return the whole function. To make this work you could concatenate the string in the loop and then return the concatenated output. You also formatted your loop incorrectly, you need to tell the loop to stop when x is less than num. Try:
function laugh(num) {
var laughString = '';
for (var x = 0; x < num; x++) {
laughString += 'ha';
}
return laughString + '!';
}
console.log(laugh(3));
You can only return once from a function. Try building up the string you need in the loop, then return the value after the loop is done.
(Note: You can have multiple return statements in a function, but as soon as you hit one of them the function completes its execution.)
function laugh(num) {
var outString = '';
for (var x = 0; x<num; x ++) {
outString += ' ha';
}
return outString.substring(1) + '!';
}
console.log(laugh(3));
function laugh(input) {
var answer = '';
for (var i = 0; i < input; i++) {
answer += 'ha';
}
return (answer + '!');
}
First, set a variable to an empty string, (it will be your answer)
Then, write a for loop that loops according to the input (you did that)
then inside the for loop you add 'ha' to your answer string
finally outside the for loop (after it has ran all the loops)
return the answer string plus !
Related
The challenge:
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Example:
spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw"
At the moment I have this
function spinWords(str) {
var splitArray = str.split(' ')
for (var i = 0; i < splitArray.length; i++) {
if (splitArray[i].length > 5) {
var long = splitArray[i].split('').reverse('').join('')
return long
i++
} else {
var short = splitArray[i]
return short
i++
}
}
}
As I said in the title, this is working properly but will only return the first element in the array as reversed or not. Can anyone smarter than me please explain why the loop is not looping?
Thank you for your time.
Return ends the function.
Another approach.
const spinWords = words =>
words
.split(" ")
.map(word => (word.length >= 5 ? [...word].reverse().join("") : word))
.join(" ");
console.log(spinWords("Hey fellow warriors"));
you are almost there..
using for loop, you do not want to do another i++..
you said that it would be 5 or more.. so it should be >=5
return terminates the for loop, so use it last..
the modified function can look like this:
function spinWords(str){
var splitArray = str.split(' ');
var spinnedWords = '';
for (var i = 0; i < splitArray.length; i++) {
if (splitArray[i].length >= 5) {
var long = splitArray[i].split('').reverse('').join('');
spinnedWords = spinnedWords.concat(' ' + long);
}
else {
var short = splitArray[i]
spinnedWords = spinnedWords.concat(' ' + short);
}
}
return spinnedWords.trim();
}
Three things must be changed for this code to work properly.
First
The return statement will finish the entire function execution. So it should be placed at the end of the body when no more code will be executed.
Second
You can switch the values you are iterating over and then return the same array with the inverted operation of the first line (.join(' ')).
Third
The for loop already increment the index counter at the end of each iteration if you defined it in the parameters. You don't need i++ inside the loop body.
function spinWords(str) {
var splitArray = str.split(' ');
for (var i = 0; i < splitArray.length; i++) {
if (splitArray[i].length >= 5) {
var long = splitArray[i]
.split('')
.reverse('')
.join('');
splitArray[i] = long;
}
}
return splitArray.join(' ')
}
EDIT: There's no need for else statement
EDIT2: I forgot the third change needed
function spinWords(str) {
return str
.split(" ")
.map(word => word.length >= 5 ? word.split("").reverse().join("") : word)
.join(" ");
}
console.log( spinWords("Hey fellow warriors") );
This is my answer after your tips:
function spinWords(str){
var splitArray = str.split(' ')
var finalArray = []
for (var i = 0; i < splitArray.length; i++) {
if (splitArray[i].length >= 5) {
var long = splitArray[i].split('').reverse('').join('')
finalArray.push(long)
}
else {
var short = splitArray[i]
finalArray.push(short)
}
}
return finalArray.join(' ')
}
I want to use function with while to print only 10 numbers starting from the number I choose.
But while loop doesn't stop looping.
id = prompt('Write any number.');
function numbering(a) {
var i = a;
var j = a + 10;
while (i < j) {
document.write(i);
i++;
}
};
numbering(id);
Try this:
var id = parseInt(prompt('Write any number.'), 10);
In your example id will be of type string and the comparisons won't work as you expect.
When you use function numbering(a) {, the variable a is passed as string.
This results in i and j being set as string.
Taking example:
Suppose you pass 2 as input, your variables will be set as a="2", i="2" and j="210". So according to your condition, it'll print starting from 2 till 209.
You can change your code to parse a as number to achieve your result; something like:
function numbering(a) {
a = parseInt(a); //parse as Int here
var i=a; var j=a+10;
while (i < j)
{
document.write(i);
i++;
}
};
Try it with a for-loop:
for(var i=0; i<10; i++){ doSomething}
You can try with this for-loop function :
id=prompt('Write any number.');
function numbering(a) {
for (let i = a; i < a + 10; i++){
document.write(i);
}
};
numbering(id);
You can add a parseInt(id) to you numbering function parameter call if you want to parse the input into a number
When you enter a number in the prompt, it is supplied as a string. Since you have not converted this into a number, the line var j = a + 10 is actually joining the two values as if they were strings.
For example, if you enter "5" into the prompt, then var j = "5" + 10 returns "510". Only when you then compare the two variables in the while loop with i < j does it get interpreted as a number, and will loop from 5 to 510.
The easiest way to convert a string into a number is to use parseInt(value).
The prompt function returns a string.
The problem is that you are concatenating a string with the number 10.
If you write your variables to document, you can see the problem:
id=prompt('Write any number.');
function numbering(a) {
var i=a; var j=a+10;
document.write(i);
document.write("<br/>");
document.write(j);
document.write("<br/>");
//while (i < j){
// document.write(i);
// i++;
//}
};
numbering(id);
This will fix your problem:
var id=parseInt(prompt('Write any number.'));
you need the parseInt function because what you getting from promt is string. For example 5 +10 . For javascript , it will be 510 .
id=prompt('Write any number.');
function numbering(a) {
var i=parseInt(a); var j=parseInt(a)+10;
while (i < j){
document.write(i);i++;
}};
numbering(id);
document.write(i +"<br>");
In console i am getting proper result. just add line break to see whole result in viewport
currently, I am on a study binge for a couple of front-end job interviews. I do going through a bunch of problems, and I am currently stuck on a problem which is not hard at all but for some reason, I can't get it to work. Maybe you guys can take a look:
The question: Add a print function to the Array Prototype that prints all the contents in the array. ex. [1,2].print() -> 1,2
I wrote this function confidently, knowing it would work, but it didn't:
Array.prototype.print = () => {
let str = ''
for(let i = 0; i < this.length; i++) {
this[i+1] === undefined ? str += this[i] : str += `${this[i]}, `
}
return str
}
console.log([1,2].print())
When I ran the function I got nothing in return. My thinking was this should have been tied with the array I was working on [1,2] but it's not. Its tied to the window.
Any idea what I did wrong? The help would be appreciated.
Best,
Ayaz
Arrow functions don't get their own value for this. Instead of:
() => {
write:
function() {
Using an arrow function binds the outer scope to this and not in the context of the Array.prototype
Array.prototype.print = function(){
let str = '';
let i = 0;
let size = this.length;
if(size === 1){
return this[0];
}
for(; i < size; i++){
str += this[i];
if(size - 1 !== i){
str += ',';
}
}
return str;
}
console.log([1].print())
console.log([1,2].print())
console.log([1,2,3].print())
var a = "gsdgtrshghf";
function reverseString(strr){
if (!strr.length){
var result="";
for(var i=strr.length;i>0;i++){
var a=strr.chatAt(i);
result+=a;
}
}return result;
}
console.log(reverseString(a))
When I tried to run it it returned me "undefined". I wonder what's the problem here.
The main reason is you are declaring var result="" and returning from outside of if(so it become undefined as its scope is only inside if statement) and other errors areas mention in comments you have a typo, charAt not chatAt. You can also simply use strr[i] to get the char. Also, you should do i-- and i >= 0 if you start at strr.length, otherwise for loop is immediately completed at the condition check. Check the below code.
var a = "gsdgtrshghf";
function reverseString(strr){
var result="";
if (strr.length){
for(var i=strr.length-1;i>=0;i--){
var a=strr.charAt(i);
result+=a;
}
}
return result;
}
console.log(reverseString(a))
Have a look:
var a = "gsdgtrshghf";
function reverseString(strr) {
var result = "";
if (strr.length != null) {
for (var i = strr.length - 1; i >= 0; i--) {
var a = strr.charAt(i);
result += a;
}
}
return result;
}
console.log(reverseString(a));
// Better
const reverse = str => Array.from(str).reverse().join('');
console.log(reverse('foo 𝌆 bar mañana mañana'));
Explanation
It's charAt(i) not chatAt(i)
Loop should start from length - 1 and end at 0 and i should be decremented
And finally declare the variable outside of if
i.e for(var i = strr.length - ; i >= 0; i--){
not for(var i=strr.length;i>0;i++){
Better yet, use combo of Array.from(str).reverse().join(''), as it even works with Unicode characters, as pointed out in comments by gaetanoM
I am trying to create a reverse function to the String type in javascript. My code is like
String.prototype.reverse = function () {
var s = "";
for(var i=this.length;i>=0;i--){
s+=this[i];
}
return s;
}
When I try to use it on for example like "test".reverse();
instead of giving "tset" it's giving "undefinedtset"
I am setting the variable like var s = ""; inside the function, still undefined is coming. Why is it so?
You just need to change var i=this.length to var i=this.length-1, because an array starts at position 0 :
String.prototype.reverse = function () {
var s = "";
for(var i=this.length-1;i>=0;i--){
s+=this[i];
}
return s;
}
this.length gives you 4 (4 letters in test word) and you start iterating from 4 to 0.
The problem is that nothing exists under 4 index (your letters are stored in 0-3 positions).
Try with:
for (var i = this.length - 1; i >= 0; i--) {
s += this[i];
}
The reason why your code isn't working has been answered by the others already, but if you want a shorter version of the reverse, you can do it like this:
String.prototype.reverse = function(){
return this.split('').reverse().join('');
}
console.log('Hello World'.reverse())