为什么我不能在一组JavaScript元素上使用Array.forEach? [英] Why can't I use Array.forEach on a collection of Javascript elements?
问题描述
let form = document。 getElementById('application-form')
let elements = form.elements
我预计可以这样做,而不是使用常规旧的
循环(这样做):
elements.forEach((el)=> {
el.disabled = true
})
但我得到 TypeError:elements.forEach不是一个函数
奇怪的是,如果我在Chrome开发控制台中的 console.log(elements)
,它就像一个数组,一堆 input
对象。它不显示对象的 Object
符号,所有键都是整数。我认为这是一种伪阵列,但我甚至不知道如何找到这个。
编辑:简短答案它不是一个数组它是一个HTMLCollection。请参阅为什么没有数据库可用于每个?
你可以。你不能这样使用 ,因为在 forEach .org / TR / html5 / infrastructure.html#htmlformcontrolscollection-0rel =nofollow noreferrer> HTMLFormControlsCollection
form.elements
给你(这不是一个数组)
以下是如何使用它:
Array.prototype.forEach.call(form.elements,function(element){
// ...
});
或者你可能可以使用传播符号:
[... elements] .forEach(function(element){
/ / ...
});
...但请注意,它依赖于 HTMLFormControlsCollection
在浏览器中执行可迭代。
或者交替 Array.from
(你需要一个polyfill,但你标记了ES2015,所以...):
Array.from(elements).forEach(function(element){
// ...
});
I'm building an app with Babel/ES6. I want to disable all form elements for a view-only version of it, so I did this:
let form = document.getElementById('application-form')
let elements = form.elements
I expected to be able to do this, instead of using a regular old for
loop (which did work):
elements.forEach((el) => {
el.disabled = true
})
but I got TypeError: elements.forEach is not a function
The strange thing is if I console.log(elements)
in the Chrome dev console it exactly like an array with a bunch of input
objects. It doesn't display with the Object
notation for objects, and all of the keys are integers. I'm thinking it's some sort of pseudo array, but I wouldn't even know how to find that out.
EDIT: short answer it's not an array it's an HTMLCollection. see Why doesn't nodelist have forEach?
You can. You just can't use it like that, because there is no forEach
property on the HTMLFormControlsCollection
that form.elements
gives you (which isn't an array).
Here's how you can use it anyway:
Array.prototype.forEach.call(form.elements, function(element) {
// ...
});
Or you may be able to use spread notation:
[...elements].forEach(function(element) {
// ...
});
...but note that it relies on the HTMLFormControlsCollection
implementation in the browser being iterable.
Or alternately Array.from
(you'd need a polyfill for it, but you tagged ES2015, so...):
Array.from(elements).forEach(function(element) {
// ...
});
For details, see the "array-like" part of my answer here.
这篇关于为什么我不能在一组JavaScript元素上使用Array.forEach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!