Jer*_*Jer 90 javascript foreach
在我的JSFiddle中,我只是试图遍历一个元素数组.正如日志语句所证明的那样,该数组是非空的.然而这个电话给forEach了我(不是那么有帮助)"Uncaught TypeError:undefinedis not a function"错误.
我必须做一些愚蠢的事; 我究竟做错了什么?
我的代码:
var arr = document.getElementsByClassName('myClass');
console.log(arr);
console.log(arr[0]);
arr.forEach(function(v, i, a) {
console.log(v);
});Run Code Online (Sandbox Code Playgroud)
.myClass {
background-color: #FF0000;
}Run Code Online (Sandbox Code Playgroud)
<div class="myClass">Hello</div>Run Code Online (Sandbox Code Playgroud)
Den*_*ret 161
那是因为 document.getElementsByClassName返回一个HTMLCollection,而不是一个数组.
幸运的是,它是一个"类似数组"的对象(它解释了为什么它被记录为好像它是一个对象以及为什么你可以使用标准for循环进行迭代),所以你可以这样做:
[].forEach.call(document.getElementsByClassName('myClass'), function(v,i,a) {
Run Code Online (Sandbox Code Playgroud)
使用ES6(在现代浏览器上或使用Babel),您还可以使用Array.from从类似数组的对象构建数组:
Array.from(document.getElementsByClassName('myClass')).forEach(v=>{
Run Code Online (Sandbox Code Playgroud)
或者将类数组的对象传播到数组中:
[...document.getElementsByClassName('myClass'))].forEach(v=>{
Run Code Online (Sandbox Code Playgroud)
小智 11
试试这个它应该工作:
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<div class="myClass">Hello</div>
<div class="myClass">Hello</div>
<script type="text/javascript">
var arr = document.getElementsByClassName('myClass');
console.log(arr);
console.log(arr[0]);
arr = [].slice.call(arr); //I have converted the HTML Collection an array
arr.forEach(function(v,i,a) {
console.log(v);
});
</script>
<style type="text/css">
.myClass {
background-color: #FF0000;
}
</style>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)