Babak Abadkheir
Babak Abadkheir

Reputation: 2348

problem with concating hash code to single string _ Java Script

I have this array :

let a = ["a", "www", "qwqwq"];

and I need to iterate in it for getting the hash of every single element. and store it in single variable as a string.

function hashCode(str) {
    var hash = 0;
    if (str.length == 0) return hash;
    for (i = 0; i < str.length; i++) {
        char = str.charCodeAt(i);
        hash = (hash << 5) - hash + char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}
let strHash = "";
for (b of a){
    strHash.concat(`${hashCode(b)}`)
}
console.log(strHash)

but I get empty string. why?

Upvotes: 0

Views: 36

Answers (2)

thedude
thedude

Reputation: 9812

concat return a new string, you need to change your code to:

for (b of a){
   strHash = strHash.concat(`${hashCode(b)}`)
}

Or, if you want a more functional approach you could do:

const strHash = a.map(hashCode).join("")

Upvotes: 4

Ali Torki
Ali Torki

Reputation: 2038

Try this way:

let a = ["a", "www", "qwqwq"];

function hashCode(str) {
    var hash = 0;
    if (str.length == 0) return hash;
    for (let i = 0; i < str.length; i++) {
        const char = str.charCodeAt(i);
        hash = (hash << 5) - hash + char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}
let strHash = [];
for (const b of a) {
    strHash.push(hashCode(b));
}
console.log(strHash.join("")) // 97118167108015397

OR this solution:

let strHash = "";
for (const b of a) {
    strHash += hashCode(b);
}
console.log(strHash) // 97118167108015397

NOTE: Your code has some javascript issues such as you didn't write var/let/const keyword before your variables in lines 6, 7, 14

Upvotes: 1

Related Questions