Wondering why I'm getting invalid left hand side assignment. Doesn't my for loop iterate through the array of string characters, get its numeric value (ASCII) and add it to count and re-assign it to the variable?
function getCharNumber(string1, string2) {
let count1 = 0
let count2 = 0
let strArray1 = string1.split('')
let strArray2 = string2.split('')
for (let i = 0; i < strArray1.length; i++) {
strArray1[i].charCodeAt(0) += count1
}
for (let i = 0; i <strArray2.length; i++) {
strArray2[i].charCodeAt(0) += count2
}
console.log(count1, count2)
}
Reverse the order at call to String.prototype.charCodeAt(). Assign the result of the call to count1, count2
for (let i = 0; i < strArray1.length; i++) {
count1 += strArray1[i].charCodeAt(0);
}
for (let i = 0; i <strArray2.length; i++) {
count2 += strArray2[i].charCodeAt(0);
}
You're getting an error, like others have stated, because you're trying to assign a value to a number.
strArray1[i].charCodeAt(0) += count1
is functionally equivalent to
12 += count1
That doesn't work b/c you can't assign anything to the number 12. Instead, you need to increment directly
strArray1[i] = String.fromCharCode(strArray1[i].charCodeAt(0) + count1)
Related
I'm writing a function to calculate investment return over period of years. However, the function seems to be only able to calculate for one year. If the totalyears is more than 1, the loop as shown below is not iterating and it returns wrong value.
const calc = (initial, monthlyContribution, totalyears, annualisedReturn) => {
let sum = initial;
for (i = 0; i < totalyears; i++) { // ISSUE: THIS NOT LOOPING WHEN totalyears > 1
let balance = sum;
let totalBalance = 0;
for (i = 0; i < 12; i++) {
totalBalance = totalBalance + balance;
balance = balance + monthlyContribution;
}
sum = balance + (totalBalance / 12) * (annualisedReturn / 100);
}
return sum;
};
console.log(calc(0, 100, 2, 10)); // This return 1255 which is wrong
You're using the same global variable for both loops. i will have the value 12 when leaving the inner loop, thus the condition of the outer loop will be false
You are using the same variable "i" in the inner loop and you are not declaring it again.
So when you start the loop with i=0, your inner loop will first make i=0 again, then it will increase until i=12, and then the same variable is used in the first loop, so it will go from 0 to 12, skipping iterations. Use "i, j,k" for nested loops.
Something like this:
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
}
}
let marks_of_students = [100,100,40]
function FindGrade(marks) {
let sum = 0;
for (let i = 0;i <= marks.length; i++) {
sum += marks[i];
console.log(sum);
}
return sum;
}
console.log(FindGrade(marks_of_students));
I don't know why I'm seeing this NaN printing along side the sum. Someone please help what did I do wrong?
You are trying to loop over the mark_of_students array with a condition i <= marks.length which means the loop will try to find marks[3] in the last iteration which doesn't exist. You need to change the condition to i < marks.length to get the desired result.
let marks_of_students = [100, 100, 40]
function FindGrade(marks) {
let sum = 0;
for (let i = 0; i < marks.length; i++) {
sum += marks[i]
}
return sum
}
console.log(FindGrade(marks_of_students))
try to convert a object into a integer by command parseInt(object) to sum.
Im javascript concatenates, NaN is not a number;
Try to do this:
parseInt("1") + parseInt("1")
instead of 1 + 1
I'm extracting number from a string and passing it to a function. I want to add 1 to it and then return the string while retaining the leading zeros. I was able to do it using a while loop but not a for loop. The for loop simply skips the zeros.
var addMoreZeros = (numStr)=> {
let newNumStr = (parseInt(numStr)+1).toString();
let zerosToAdd = numStr.length - newNumStr.length;
let zeroPadStr = "";
let i = 0;
while (i < zerosToAdd) {
zeroPadStr += "0";
i++;
}
//This doesn't work
//for(let i = 0; i++; i < zerosToAdd) {
// zeroPadStr+="0";
//}
return zeroPadStr + newNumStr;
}
You have your for loop syntax wrong, it should be:
(initializer; condition; increments / decrements)
so:
for(let i = 0; i < zerosToAdd; i++) {}
var addMoreZeros = (numStr)=> {
let newNumStr = (parseInt(numStr)+1).toString();
let zerosToAdd = numStr.length - newNumStr.length;
let zeroPadStr = "";
for(let i = 0; i < zerosToAdd; i++) {
zeroPadStr+="0";
}
return zeroPadStr + newNumStr;
}
console.log(addMoreZeros("00125"))
Alternative approach (instead of using for/while):
var addMoreZeros = (numStr, numLength = numStr.length) => `${++numStr}`.padStart(numLength,'0');
// example of usage
console.log(addMoreZeros("124", 5));
Explanation ++numStr coerces the numeric string to a number and increments it, then `${...}` casts the number back to a string. Finally padStart() adds leading zeros.
Can someone tell me why this bit of JavaScript is buggy?
I have HTML also, but I don't want to make this a massive code dump.
<script type = 'text/javascript'>
var playerCards = [];
var dealerCards = [];
function deal() {
var newCard = Math.random() % 12;
var newCard2 = Math.random() % 12;
playerCards += newCard;
playerCards += newCard2;
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
document.getElementById("playerTotal").innerHTML = counter;
var dCounter = 0;
for (var j = 0; j < playerCards.length; ++j) {
dCounter += j;
}
document.getElementById("dealerTotal").innerHTML = dCounter;
}
</script>
I'm gonna assume this is a silly syntax error someplace, but I can't find it.
I'm guessing that this isn't doing what you expect it to:
playerCards += newCard;
playerCards += newCard2;
Try this instead:
playerCards.push(newCard);
playerCards.push(newCard2);
The first snippet is trying to "add" a number to an array, which doesn't exactly make sense. Through some arcane JavaScript rules, this turns the result into a string.
I'm guessing that you want to concatenate to an array instead.
Math.random returns a number between 0 and 1 - so Math.random() % 12 will probably be zero
var playerCards = [];
playerCards += newCard; //
what are you even trying to do there?
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
if playerCards had a length, this loop would result in counter having value of 0, 1, 3, 6, 10 .. n(n+1) / 2 - probably not what you intended, but who knows
I need help in somewhere in javascript
var obj = jQuery.parseJSON(data.d);
This ajax call result returns some data (around 31).
Here is an example:
obj[0] = 10, obj[1]=20 ,obj[2]=30 , obj[4]=21,obj[5]=16,obj[6]=54 here I want to get value of
obj[0] and ob[4] using for loop . And I also need to do this for obj[10] and obj[14] the difference will be 5 between the i values .
Any idea or help?
You can do something like this (a pseudo code)
int i = 0;
while(i < 31)
{
print(i);
i = i + 4;
}
If i understood, you want to skip 5 on each step:
var array = 'abcdefghijklmnopqrstuvwxyz'.split(''); // something that generates an array just to show an example
var i = 0;
for (; i < array.length;) {
console.log(i, array[i]);
i += 5;
}
see fiddle
var iterator=0;
for (i = 0; i < obj.length; i++) {
if(i == iterator){
alert(obj[iterator]);
iterator= iterator + 4;
}
}