1

This is in discord.js. So I have three items each with a unique price (more items in the future).. Sending the name of the item for example "Item 1" should reply the price. How do I use the price variable in my code? I was thinking associative array but I think there's no associate array in JS.

  1. Item 1 = 100
  2. Item 2 = 300
  3. Item 3 = 500

I have this code:

const items = ["Item 1", "Item 2", "Item 3"];
const price = [100, 300, 500];

for (var i=0; i < items.length; i++) {
if (message.content === items[i]) {
message.reply(PostPrice);
}
}
2
  • 1
    using the index? price[i]? Commented Nov 11, 2022 at 20:23
  • oh i see. thanks. i thought i should use something like associative array, so doing it this way works. Commented Nov 11, 2022 at 20:26

2 Answers 2

3

I would use a Map, a built-in object in javascript

const items = new Map()
//create map
items.set("item 1",100)
items.set("item 2",300)
items.set("item 3",500)

//check if item exists
if(items.has(message.content.toLowerCase())){
  message.reply("price: "+items.get(message.content.toLowerCase()))
}else{
  message.reply("this item doesnt exist");
}

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

1 Comment

You could make this more user friendly by using message.content.toLowerCase() instead of message.content and make the items also lower case because some people don't use capitalization in discord
1

I would use json instead of arrays in this case

const items = {"item 1": { price: 100 }, "item 2": { price: 300 }, "item 3": { price: 500 }}

if(items[message.content.toLowerCase()) {
message.reply("price: "+items[message.content.toLowerCase()]["price"])
} else {
message.reply("item doesnt exist")
}

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.