I am trying to access the length of an array I made inside a function. How do I use the this
to access it?
Here is my code:
let hashtable = new Arrary(50)
// create a hashfunction
let gethash = (key)=>{
// make sure all value passed in are strings
let keyStr = key.toString();
let sum = 0
for (let i = 0; i < keyStr.length; i++) {
sum =+ keyStr.charAt(i)
}
return sum % this.hashtable.length
}
I am learning hashmaps in data structures and algorithms. I would like to use the length of the hash table to ensure that my hash function falls between the size of the array.
Does it not work without the this
keyword?
let hashtable = new Arrary(50)
// create a hashfunction
let gethash = (key)=>{
// make sure all value passed in are strings
let keyStr = key.toString();
let sum = 0
for (let i = 0; i < keyStr.length; i++) {
sum =+ keyStr.charAt(i)
}
return sum % hashtable.length
}
You aren't accessing something bound to a class or object, so you should be able to treat it like a normal variable.
More about the this
keyword:
In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).