0

My question is instead of inheriting the array prototype Is there some way we can manipulate associative arrays to use them as Hashmaps with functions like getKey,getValue,ContainsKey,ContainsValue?

2
  • 1
    JavaScript is not PHP, there are no "associative arrays". You can use objects or Map. Commented Oct 12, 2018 at 12:32
  • Thanks for the nudge in the right direction. Commented Oct 12, 2018 at 12:36

1 Answer 1

2

You can use the Map class that Javascript provides:

const map = new Map();

map.set("key", 23);
console.log(map.get("key")); // 23
console.log(map.has("key")); // true

An alternative that works as well and is kinda a basic concept of Javascript are normal Objects since they behave like maps. Eventhough you can use normal objects, I recommend using Map.

const obj = {
  "key": 23
}

console.log(obj["key"]); // 23

obj["another key"] = 420;

console.log(obj["another key"]); // 420

// and the ugly version of Map.has:
console.log(obj["key"] !== undefined); // true

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.