繁体   English   中英

Object.keys()返回属性

[英]Object.keys() returns properties

这个SO答案中,他说Object.keys()获得在对象本身上定义的属性(那些true for obj.hasOwnProperty(key)返回true for obj.hasOwnProperty(key)但是下面的代码返回4 keys并且还会产生错误,这使我感到困惑。

 (function () { "use strict"; var buttons = document.getElementsByClassName('remove'); console.log("No of keys: ", Object.keys(buttons).length); for ( var i in Object.keys( buttons ) ) { buttons[i].onclick = function() { this.parentElement.remove(); console.log(this.id); }; } })(); 
 <div>Some entry here <button id="0" class="remove">Remove</button> </div> <div>Another entry here <button id="1" class="remove">Remove</button> </div> 

如何在javascript中正确执行此操作?

不仅true for obj.hasOwnProperty(key)条件为true for obj.hasOwnProperty(key) ,而且还必须将名为enumerable的属性属性之一设置为true

那你的代码呢? 让我们看看什么是buttons 您会看到这是一个对象,其中包含7个属性。 Chrome中仅显示4个属性,因为它们可以枚举

 (function () { "use strict"; var buttons = document.getElementsByClassName('remove'); console.log(buttons); })(); 
 <div>Some entry here <button id="0" class="remove">Remove</button> </div> <div>Another entry here <button id="1" class="remove">Remove</button> </div> 

因此,当您尝试执行此代码时

 (function () { "use strict"; var buttons = document.getElementsByClassName('remove'); for ( var i in Object.keys( buttons ) ) { console.log(i); } })(); 
 <div>Some entry here <button id="0" class="remove">Remove</button> </div> <div>Another entry here <button id="1" class="remove">Remove</button> </div> 

它实际上是从Object.keys返回的数组的indexes 1,2,3,4 ,但是您的buttons对象中没有名称为2, 3, 4的属性。 那么为什么会出现错误。 使用forEach函数迭代每个属性并添加事件侦听器。

 (function () { "use strict"; var buttons = document.getElementsByClassName('remove'); Array.prototype.forEach.call(buttons, button => { button.addEventListener('click', function() { this.parentElement.remove(); console.log(this.id); }); }); })(); 
 <div>Some entry here <button id="0" class="remove">Remove</button> </div> <div>Another entry here <button id="1" class="remove">Remove</button> </div> 

因此,这是使用for循环从原始代码中循环遍历buttons

 (function () { "use strict"; var buttons = document.getElementsByClassName('remove'); console.log(buttons); for (var index = 0 ; index < buttons.length ; ++index) { buttons[index].onclick = function() { this.parentElement.remove(); console.log(this.id); }; } })(); 
 <div>Some entry here <button id="a" class="remove">Remove</button> </div> <div>Another entry here <button id="b" class="remove">Remove</button> </div> 

请注意, buttons对象是HTMLCollection 这通过索引和ID公开了元素。 在您的原始示例中,您的id是01 ,在这种情况下,这很令人困惑,因为它导致它们与索引冲突。 Object.keys(buttons)返回['0', '1', '0', '1'] ,这有点奇怪,大概是由于一些数字/字符串的恶作剧。 我已经将示例中的id更改为ab所以现在Object.keys(buttons)将是['0', '1', 'a', 'b']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM