最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I use HTML elements as Object keys? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to create an Object with HTML elements as keys. I create the keys using document.createElement('div'), but when I try to insert both into an Object the second key ends up replacing the first:

let a = document.createElement('div');
let b = document.createElement('div');

let obj = {};
obj[a] = 3;
obj[b] = 'x';

console.log(obj);

I'm trying to create an Object with HTML elements as keys. I create the keys using document.createElement('div'), but when I try to insert both into an Object the second key ends up replacing the first:

let a = document.createElement('div');
let b = document.createElement('div');

let obj = {};
obj[a] = 3;
obj[b] = 'x';

console.log(obj);

Is there a way to do this without any keys or values getting replaced?

Share Improve this question edited Feb 15, 2021 at 14:40 pretzelhammer 15.2k16 gold badges53 silver badges103 bronze badges asked May 22, 2020 at 14:16 ketanketan 19.4k42 gold badges68 silver badges104 bronze badges 9
  • 1 what are you trying to do , what is your use case ? – ashish singh Commented May 22, 2020 at 14:18
  • 1 You could use Map instead of an plain object. – Sirko Commented May 22, 2020 at 14:18
  • This question was asked me on interview. But, couldn't find answer. – ketan Commented May 22, 2020 at 14:22
  • 1 What exactly was the interview question? Pretty sure you misunderstood what they wanted. – Guy Incognito Commented May 22, 2020 at 14:25
  • 1 Whenever a key is added to an object, it internally does String(key). Both String(a) and String(b) return "[object HTMLDivElement]". It's still unclear what the question is. Did your interview ask how can we use an HTML element as the key of an object? – adiga Commented May 22, 2020 at 14:32
 |  Show 4 more ments

2 Answers 2

Reset to default 9

Objects can only hold string keys. Your divs are being serialized to strings and then overriding each other. If you would like to hold HTML Elements as keys you should use a Map like so:

let a = document.createElement('div');
let b = document.createElement('div');

let map = new Map();
map.set(a, 3);
map.set(b, 'x');

// use Array.from to pretty print the result
console.log(Array.from(map));

When you use a to create a key in an object

let a = document.createElement('div');
obj[a] = 3;

It assigns the object the string representation of a which is "[object HTMLDivElement]"

console.log(obj); // { "[object HTMLDivElement]": 3 }

So when you assign b

obj[b] = 'x';

what you're really saying is

obj["[object HTMLDivElement]"] = 'x'

and "[object HTMLDivElement]" already exists in the object, so it assigns it the new value of 'x'

console.log(obj); // { "[object HTMLDivElement]": "x" }
发布评论

评论列表(0)

  1. 暂无评论