Recommand · October 14, 2021 0

Javascript Array[Variable] Reference Problems

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)

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'

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());

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])

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")