Home > Blockchain >  Javascript Array[Variable] Reference Problems
Javascript Array[Variable] Reference Problems

Time:10-14

let string = ['h', 'e', 'l', 'l', 'o'];
let count = 0;
let part = string[count];
console.log(part); // logs out 'h'
count   ;
console.log(part); // still loggs out 'h'

I would like for the second log to log out 'e' instead of 'h'. Because I've updated code to 1 instead of 0.

Edit: I understand that I can just keep using the string[count] reference but I was asking if there was a way to do what I have described with a variable. (Make it reactive)

CodePudding user response:

when you initialize part, you are setting it equal to 'h'. Despite incrementing count, that will not change part as it is still h. Thus, you will need to set part equal to string[count] again, after incrementing count.

let string = ['h', 'e', 'l', 'l', 'o'];
let count = 0;
let part = string[count];
console.log(part); // logs out 'h'
count   ;
part = string[count];
console.log(part); // now logs 'e'

CodePudding user response:

You can make part a function, then call it whenever you want to get the item at index count:

let string = ['h', 'e', 'l', 'l', 'o'];
let count = 0;
let part = () => string[count];
console.log(part());
count   ;
console.log(part());

CodePudding user response:

If you want it dynamic based off counter don't create the part reference.

let string = ['h', 'e', 'l', 'l', 'o'];
let count = 0;
console.log(string[count]) // logs out 'h'
count   
console.log(string[count])

CodePudding user response:

function countChars(string,char)
{
    int count = 0;
    for (int i=0; i < string.length(); i  )
    {
        if (string(i) == char)
        {
             count  ;
        }
    }
    return count;
}

console.log(countChars("hello", "l")
  • Related