为什么我不能在 Javascript 元素集合上使用 Array.forEach? [英] Why can't I use Array.forEach on a collection of Javascript elements?

查看:18
本文介绍了为什么我不能在 Javascript 元素集合上使用 Array.forEach?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Babel/ES6 构建一个应用程序.我想禁用它的仅查看版本的所有表单元素,所以我这样做了:

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

我希望能够做到这一点,而不是使用常规的旧 for 循环(确实有效):

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
})

但是我得到了 TypeError: elements.forEach is not a function

奇怪的是,如果我在 Chrome 开发控制台中 console.log(elements) 它就像一个带有一堆 input 对象的数组.它不以对象的 Object 表示法显示,并且所有的键都是整数.我认为这是某种伪数组,但我什至不知道如何找到它.

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:简而言之,它不是数组,而是 HTMLCollection.参见 为什么 nodelist 没有 forEach?

EDIT: short answer it's not an array it's an HTMLCollection. see Why doesn't nodelist have forEach?

根据 这个答案nodelist 现在有 forEach方法!

Per this answer, nodelist now has the forEach method!

推荐答案

可以.你不能像那样使用它,因为 HTMLFormControlsCollection form.elements 给你(不是数组).

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, (element) => {
    // ...
});

或者在现代浏览器上,您可以利用底层 HTMLCollectioniterable 的事实,即使它没有 forEach:

Or on modern browsers you can make use of the fact that the underlying HTMLCollection is iterable even though it doesn't have forEach:

// `for-of`:
for (const element of elements) {
    // ...do something with `element`...
}

// Spreading into an array:
[...elements].forEach((element) => {
    // ...do something with `element`...
});

但这不适用于 IE11 等过时的浏览器.

That won't work on obsolete browsers like IE11 though.

还有 Array.from(对于过时的浏览器需要一个 polyfill):

There's also Array.from (needs a polyfill for obsolete browsers):

Array.from(elements).forEach((element) => {
    // ...
});

有关详细信息,请参阅部分in-javascript/9329476#9329476">我的回答在这里.

For details, see the "array-like" part of my answer here.

这篇关于为什么我不能在 Javascript 元素集合上使用 Array.forEach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆