adding and subtracting to the array range - javascript

Hey I have a question about this piece of code that I have:
var levelsRange = arrayeventslevel[0] + " through " + arrayeventslevel[arrayeventslevel.length-1]; ;
$("#existorders").html(
"There are currently: " + arrayeventslength.length +
" events on " + dayoftheweek +
"<br/>" + " with order levels: " + levelsRange +
"<br />" + "You can move new event to levels ranging between: " + newLevelsRange
);
currently levelsRange outputs for example 1 through 6 range. If that is the case,
I need another variable newLevelsRange that should say 0 through 7 based on initial variable range.
However, if levelsRangesays 0 through 6, new variable should say 0 through 7 NOT -1 through 7
I am having trouble adding subtracting properly from initial variable information. Can someone please assist.

var newLevelsRange=(arrayeventslevel[0]||1)-1 + " through " + (arrayeventslevel[arrayeventslevel.length-1]-1);
Simply check if the first element is zero, if so, take 1...

I just did this
if(arrayeventslevel[0] != 0){
arrayeventslevel[0] = arrayeventslevel[0] - 1;
arrayeventslevel.length =arrayeventslevel.length + 1;
}
var newLevelRange = arrayeventslevel[0] + " through " + arrayeventslevel.length;
not sure how to use Math.max

Related

How to concatenate two variables in a array

I am pushing values to a empty array using push(), but when I console log the array I am getting a single character per line. I am trying to concatenate two variables into one line/space.
// Example
walking.CordX = 5;
walking.CordY = 2;
walking.wLog.push("x" + " " + walking.cordX, "y" + " " + walking.cordY);
console.log(wLog);
//Will Show
1: x5
2: y2
How can I change it to get it like:
1: x5 y2
You can simply use multi-line syntax from es6.
let arr = [], x=5, y=7;
arr.push(`x${x} y${y}`);
console.log(arr);
walking.wLog.push("x" + " " + walking.cordX + " " + "y" + " " + walking.cordY);
This should work.

How to add an ascending number to every 6th item in an array?

I would like to add an ascending number to every 6th item of an array. So far I have this but at the moment it adds an ascending number to every line, not every 6th line. Can someone say how to fix that? Thanks
for(var i=0;i<newlist.length;i++){
newlist[i]=counter + "." + " " + newlist[i];
counter++;
}
i++ increments the index by one, i += 6 increments the index by 6.
If you want to iterate over 1 to 1 and add a flag that increments on every 6 line iterated, you need another logic:
for(var i=0;i<newlist.length;i++){
newlist[i]=counter + "." + " " + newlist[i];
if (i%6==0)
counter++;
}
Edit:
If you want to create the line every 6 iteration:
for(var i=0;i<newlist.length;i++){
if (i%6==0)
newlist[i]=counter + "." + " " + newlist[i];
}
Arrays in javascript are 0 based so assuming that you want every 6th element to contain the prefix -
for(var i=0;i<newlist.length;i++) {
if ( (i+1) % 6 === 0) {
newlist[i] = ((i+1)/6) + "." + " " + newlist[i];
}
}

How to return a String representation of a calculation in Javascript

I am currently trying to complete an assignment for an intro2Javascript course. The question basically asks me to return a string of multiples of 2 parameters (num, numMultiple). Each time it increments the value i until i = numMultiple. For example:
5 x 1 = 5\n
5 x 2 = 10\n
5 x 3 = 15\n
5 x 4 = 20\n
This was my attempt:
function showMultiples(num, numMultiples) {
var result;
for (i = 1; i <= numMultiples; i++) {
result = num * i
multiples = "" + num + " x " + i + " = " + result + "\n"
return (multiples)
}
}
...and because the assignment comes with pre-written console logs:
console.log('showMultiples(2,8) returns: ' + showMultiples(2, 8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3, 2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5, 4));
console.log('\n');
This is my output:
showMultiples(2,8) returns: 2 x 1 = 2
Scratchpad/1:59:1
showMultiples(3,2) returns: 3 x 1 = 3
Scratchpad/1:60:1
showMultiples(5,4) returns: 5 x 1 = 5
UPDATE
You were doing two things incorrectly:
1) You were returning after the first iteration through your loop
2) You were assigning to multiples instead of appending to it.
Since you want to gather all the values and then show the final result first, I add all of the values to an array, and then use unshift() to add the final element (the result) to the beginning of the array. Then I use join() to return a string representation of the desired array.
function showMultiples(num, numMultiples) {
var result;
var multiples = [];
for (let i = 1; i <= numMultiples; i++) {
result = num * i
multiples.push("" + num + " x " + i + " = " + result + "\n")
}
multiples.unshift(multiples[multiples.length-1]);
return (multiples.join(''))
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2, 8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3, 2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5, 4));
console.log('\n');
You need to declare all variables, because without you get global variables (beside that it does not work in 'strict mode').
The second point is to use multiples with an empty string for collecting all intermediate results and return that value at the end of the function.
For keeping the last result, you could use another variable and append that value at the end for return.
function showMultiples(num, numMultiples) {
var i,
result,
multiples = "",
temp = '';
for (i = 1; i <= numMultiples; i++) {
result = num * i;
temp = num + " x " + i + " = " + result + "\n";
multiples += temp;
}
return temp + multiples;
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2, 8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3, 2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5, 4));
As other answers say, your problem is in multiple.
You are clearing multiple every iteration and storing the new value, but you do not want that, you want to add the new result, and to do so you use this code:
multiples = multiple + "" + num + " x " + i + " = " + result + "\n"
which can be compressed in what the rest of the people answered:
multiples += "" + num + " x " + i + " = " + result + "\n"
Probably you already know, but to ensure:
a += b ---> a = a + b
a -= b ---> a = a - b
a *= b ---> a = a * b
and there are even more.

If/else inside function JavaScript

Please don't be too hard on me as I've just started in school and I'm using Ubuntu. I've written this code (which might be the simplest code ever) that simply tells about the conversion of bytes into other units (Mebi, Kibi...). When I use the console.log it always displays Kibi.
function unit(x){
var x;
if (x=10){
x='Kibi';
} else if (x=20){
x='Mebi';
} else if (x=30){
x='Gibi';
}
return x;
}
console.log("2^10 bytes are 1 " + unit(10) + "byte");
console.log("2^20 bytes are 1 " + unit(20) + "byte");
console.log("2^30 bytes are 1 " + unit(30) + "byte");
The thing here is that as I said it always displays Kibi on all console outputs, the funny thing for me that I don't understand is that if I change the first console.log for
console.log('2^10 bytes are 1 ' + unit(20) + 'byte'
it will still display all console outputs with Kibi even if I never called unit(10).
I really don't understand why this is happening and any help would be greatly apprecieated. Thank you.
you've declared variable x and not set value for it, and = just for left assign follows my code
Heres my code:
function unit(x){
var nickname = '';
if (x===10){
nickname='Kibi';
} else if (x===20){
nickname ='Mebi';
} else if (x===30){
nickname ='Gibi';
}
return nickname;
}
console.log("2^10 bytes are 1 " + unit(10) + "byte");
console.log("2^20 bytes are 1 " + unit(20) + "byte");
console.log("2^30 bytes are 1 " + unit(30) + "byte");
your codes error:
variable x redeclared
x=10 means let 10 assigns to variable x.
hopes to help you
edited:
for your question, maybe this code will be better
function unit(x){
var nickname = '';
switch(x){
case 10:
nickname = 'kibi';
break;
case 20:
nickname = 'Mebi';
break;
case 30:
nickname = 'Gibi';
break;
}
return nickname;
}
console.log("2^10 bytes are 1 " + unit(10) + "byte");
console.log("2^20 bytes are 1 " + unit(20) + "byte");
console.log("2^30 bytes are 1 " + unit(30) + "byte");
I tell you
Variables should not have ambiguity, one variable do one thing.
you can follow to #epascarello and #Keith advice
All that is changed in this snippet was exactly what the two comments suggested. Remove the extra initialization of x and change "=" to "==" in the comparisons.
function unit(x){
if (x == 10){
x='Kibi';
} else if (x == 20){
x='Mebi';
} else if (x == 30){
x='Gibi';
}
return x;
}
console.log("2^10 bytes are 1 " + unit(10) + "byte");
console.log("2^20 bytes are 1 " + unit(20) + "byte");
console.log("2^30 bytes are 1 " + unit(30) + "byte");

Printing Javascript split() array and converting undefined values to strings

I am trying to convert a string to words, and then print these using javascript and html5 canvas. The string can be any length, but I am using 50 as a max value of words (separated by a space). Right now I have the following to create the array:
var wordArray = kstring.split(" ", 50);
for(var k = 0; k < wordArray.length; k++)
{
if(typeof wordArray[k] == 'undefined')
wordArray[k] = " .";
}
and then print using:
ctx.fillText(wordArray[0] + " " + wordArray[1] + " " + wordArray[2] + " " + wordArray[3] + " " + wordArray[4], leftOffset, txtHeight);
ctx.fillText(wordArray[5] + " " + wordArray[6] + " " + wordArray[7] + " " + wordArray[8] + " " + wordArray[9], leftOffset, txtHeight+20);
etc.
However, when the text prints, any undefined values print as "undefined" instead of " ." It seems that I am going about checking for the undefined value the wrong way, but I'm not sure what else to try.
Additionally, if anyone has any better suggestions for how to achieve this goal (convert a string to words and then print 5 words at a time). Please feel free to suggest some better options.
Thanks
There won't be any undefined values in the array returned by .split(). You're getting undefined because your print code has hardcoded indexes higher than the highest index in the array.
Sorry, I don't have time right now to test this, or explain it beyond mentioning that .slice() creates a new array extracting a range from the source array, and .join() is (obviously) the opposite of .split(), but maybe you could try something like this:
var wordArray = kstring.split(" ", 50),
i, h, l
wordsPerLine = 5,
lineHeight = 20;
for (i=0, h=0, l=wordArray.length; i < l; i+=wordsPerLine, h+=lineHeight) {
ctx.fillText( wordArray.slice(i, Math.min(l, i+wordsPerLine)).join(" "),
leftOffset, txtHeight + h);
}

Categories