I need to print a range of numbers in a range using a function and a for-loop.
Again I'm stuck on the return value. I believe my code is sufficient for the task but if you have a better idea I'm all ears.
function printRange(rangeStart, rangeStop) {
var text = "";
for (var i = rangeStart; i < rangeStop; i++) {
text += i + ',';
}
return text;
var result = text;
}
printRange(20, 47);
The 'result' is ought to print the numbers 20,21,22...,46,47 but of course it doesn't...
Any help is appreciated.
Regards, Thomas
There are two things you need to fix - your code doesn't print rangeStop, but it does include a trailing comma.
You can fix the former by changing your loop end condition to use <=, and String.prototype.slice can do the latter.
function printRange(rangeStart, rangeStop) {
var text = "";
for (var i = rangeStart; i <= rangeStop; i++) {
text += i + ',';
}
return text.slice(0, -1);
}
document.write(printRange(20, 47));
function printAllNum(rangeStart, rangeEnd){
for(let i = rangeStart; i <= rangeEnd; i++) {
document.write(i + " ")}
}
printAllNum(1,20);
Related
I'm trying to make a program where if you write in a word, let's say "Hello". And then you press the print button the outcome would be this:
"H"
"He"
"Hel"
"Hell"
"Hello".
Should i use a loop for this? My code so far is this:
function printit()
{
var temptext = document.getElementById("mytext").value;
temptext = temptext.slice(1,2);
document.getElementById("translated").innerHTML=temptext;
}
Anyone got any suggestions on how to solve this?
Here's how this would work with a loop.
Loop over the characters
Use the loop counter (i) to progressively slice the required chunk off your text.
Make sure you slice(0, i + 1), so you don't slice(0, 0) on the 1st iteration
function print() {
var text = document.querySelector("#text").value
for(var i = 0; i < text.length; i++) {
console.log(text.slice(0, i + 1))
}
}
<input id="text" value="Hello"/>
<button onclick="print()">Print</button>
You can use .map() with a scoped variable, to return an array of the words you need
function toSplicedWordArray(what) {
var before='';
return what.split('').map(function(item) {before+=item;return before;});
}
console.log(toSplicedWordArray('hello'));
try this:
let word = 'Good';
for (let i = 1; i <= word.length; i++) {
console.log(word.substring(0, i));
}
function printinit() {
var tempText = document.getElementById("mytext").value;
var slicedText = "";
for (var i = 0; i < tempText.length; i++) {
slicedText = tempText.slice(0, i) + " ";
}
document.getElementById("translated").innerHTML = temptext;
}
The code below should reverse all the characters in a sentence, but it is unable to do so. This is child's play to me but at this moment it's not compiling. Can anyone figure out the issue?
Let's say:
"Smart geeks are fast coders".
The below code should reverse the above string as follows:
"trams skeeg era tsaf sredoc"
function solution(S){
var result = false;
if(S.length === 1){
result = S;
}
if(S.length > 1 && S.length < 100){
var wordsArray = S.split(" "),
wordsCount = wordsAray.length,
reverseWordsString = '';
for(var i = 0; i< wordsCount; i++){
if(i > 0){
reverseWordsString = reverseWordsString + ' ';
}
reverseWordsString = reverseWordsString + wordsAray[i].split("").reverse().join("");
}
result = reverseWordsString;
}
return result;
}
This should give you the result you're looking for.
function reverseWords(s) {
return s.replace(/[a-z]+/ig, function(w){return w.split('').reverse().join('')});
}
function reverseWords(s) {
var arr = s.split(" ");
s = '';
for(i = 0; i < arr.length; i++) {
s += arr[i].split('').reverse().join('').toLowerCase() + " ";
}
return s;
}
Wouldn't that do the job for you? Basically it just converts the string into an array, by splitting it on space. Then it loops over the array, adds every string reversed to a new string, and then it converts it to lowercase. For faster speed (nothing you would notice), you can just call newStr.toLowerCase() after the loop, so it will do it once instead of every time.
I need to count numbers upward and have it print out with a string "then" in between: 5 then 6 then 7 then... like this. I am very confused with using the parameters vs function name when you return. My code is below.. but could someone help with this?
function countUp(start) {
start +=
for(var i = start; i < start + 10; i++) {
console.log(start[i] + "then");
}
return start;
}
I would do something like this:
function countSheep(limit){
for (var i = 1; i < limit; i +=1){
console.log(i + " sheep")
}
}
countSheep(10);
I used "sheep" instead of "then", but you get the idea. Since you just want to produce a side effect (print out a "1 then 2.." to the console, you don;t need to build up a string and then have your function return it.
If you did want to build up a string and then have your function return it though, you could do something like this instead:
function countSheep(limit){
var allMySheep = "";
for (var i = 1; i < limit; i +=1){
allMySheep += (i + " sheep, ")
}
return allMySheep;
}
console.log(countSheep(10));
Note: I started my loops at 1 (var i = 1) because I'm counting sheep, not numbers. You'd probably want to start yours at 0 (var i = 0).
We can use JavaScript join function as well to achieve this
Code
function getCountStr(count) {
var str =[];
for (var i = 1; i <= count; i++) {
str.push(i);
}
console.log(str.join(' then '));
}
There are few issues with your code
function countUp(start) {
start += // <<<<< what's this? It's an incomplete (and useless) statement
for(var i = start; i < start + 10; i++) {
console.log(start[i] + "then");
// ^^^^^^^^ why are doing this? you should only write i
}
return start; // you don't need to return anything
}
A cleaned and working version from your code
function countUp(start) {
for(var i = start; i < start + 10; i++) {
console.log(i + " then ");
}
}
But this code will have an extra 'then' at the end like 1 then 2 then, so here's a code that will handle this
function countUp(start) {
// a temporary array to store your numbers
var tmpArr = [];
for (var i = start; i < start + 10; i++) {
// store the count into the array
tmpArr.push(i);
}
// display the count by putting ' then ' between each number
var stringToDisplay = tmpArr.join(' then ');
console.log(stringToDisplay);
document.write(stringToDisplay);
}
countUp(1);
I just started learning JavaScript and I'm extremely annoyed by it.
I want a procedure that decompresses a string of decimal digits like so:
"301051" means "3 zeros, a one, a zero, then 5 ones"
i.e.
"301051"---> "0001011111"
A string of digits of ones and zeros won't be changed at all (and also won't have any more than two consecutive 0's or 1's)
"01001100" ---> "01001100"
I started to work on it, but I'm churning out spaghetti code.
for (i = 0; i < thisString.length;)
{
thisNum = thisString.charCodeAt(i);
if (thisNum > 1)
{
substr = "";
for (j = 0; j < thisNum; j++)
subtr += thisString.charAt(i);
if (i == 0)
thisString = substr + thisString.substring(2
}
}
I don't feel like finishing that because I'm sick of using the limited number of JavaScript string functions. I'm sure the geniuses at Stack Overflow have a 1-line solution for me. Right, guys????
Here's a simple algorithmic solution:
function decompress(str) {
var result = "", char = "";
for (var i = 0; i < str.length; i++) {
char = str.charAt(i);
console.log(char - '0');
if (char > 1) {
result += new Array(+char + 1).join(str.charAt(++i));
} else {
result += char;
}
}
return result;
}
And an even simpler regex solution:
function decompress(str) {
return str.replace(/([2-9])(.)/g, function(m, a, b) {
return new Array(+a + 1).join(b);
});
}
The only magic here is the new Array(+a + 1).join(b) (which is also used by both solutions). The first + turns a (or char) into a number. Then I create an array of a + 1 elements, and join them together with following character as 'glue'. The result is a string of a repetitions of b.
I believe you need something like:
function decompress(thisString) {
var result = '';
for (var i = 0; i < thisString.length; i += 2) {
var thisNum = parseInt(thisString[i], 10);
if (thisNum > 1) {
for (var j = 0; j < thisNum; j++)
result += thisString[i + 1];
} else {
result += (thisString[i] + thisString[i + 1]);
}
}
return result;
}
You have a lot of variables, which are leaking as globals. Make sure you declare each of them using var.
New to the JavaScript language and need help creating a function which generates the following display.
abcdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyz
cdefghijklmnopqrstuvwxyz
defghijklmnopqrstuvwxyz
.... and so on, all the way down to
xyz
yz
z
I am not asking for handouts, just a little kickstart for a beginner to get started! Links, hints, tips, anything helps! Thanks!
Arrays and loops are powerful when combined.
var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
console.log(alphabet.join(''));
while (alphabet.length > 0) {
alphabet.shift();
console.log(alphabet.join(''));
}
Edit:
If you really need your decremented alphabet to be left-padded, you can use this:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var letters = alphabet.split('');
var addPadding = (function (minLength) {
return function (shortString) {
if (shortString.length < minLength) {
return new Array(
minLength - shortString.length + 1
).join(' ') + shortString;
}
};
}(alphabet.length));
console.log(alphabet);
while (letters.length > 0) {
letters.shift();
console.log(addPadding(letters.join('')));
}
Edit:
Here is a much simpler answer:
function decrementingAlphabet () {
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
function iterate(spaces, letters) {
if (letters.length > 0) {
console.log(spaces + letters);
iterate(spaces + ' ', letters.substring(1));
} else {
return;
}
}
iterate('', alphabet);
}
This is simple example.
var str = '';
for (var s=0; s < 26; ++s) {
str = '';
for (var i=0; i < 26 - s; ++i) {
str += String.fromCharCode(97+s+i);
}
document.write(str + "<br/>");
}
See http://jsfiddle.net/G5Gds
Hmm, maybe this will help put you on the right track?
var str = '';
// Find out what 'a' is in ASCII
var baseLetterCode = 'a'.charCodeAt(0);
// Loop once for each letter
for (var i = 0; i < 26; ++i) {
// Append to string
str += String.fromCharCode(baseLetterCode + i);
}
In character codes, small alphabets lie from 97 onwards(97 for a). You need to use 2 for loops to print such series.
Here is your jsfiddle demo:
var display='';
for(var i=97;i<123;i++){
var s='';
for(var j=i;j<123;j++){
s+= String.fromCharCode( j );
}
display+=s;
}
alert(display);
(function() {
var theENalphabet = [];
for (var charNow = "a".charCodeAt(0); charNow <= "z".charCodeAt(0); charNow += 1) {
theENalphabet.push(String.fromCharCode(charNow));
}
var isNow = 0;
function decrAlph(startAt) {
var alphString = "";
for (var i = startAt; i < theENalphabet.length; i += 1) {
alphString += theENalphabet[i];
}
console.log(alphString);
isNow++;
while (isNow < theENalphabet.length) {
decrAlph(startAt + 1);
}
};
decrAlph(0);
})();
The charCode getting could be abstracted into a function:
var getCharCode = function(el){
return String.prototype.charCodeAt.call(el, 0);
};
getCharCode("a"); // returns 97..