coffeescript -数组过滤不工作

coffeescript - Array filtering not working

本文关键字:工作 过滤 数组 coffeescript      更新时间:2023-09-26

我试图获得一个数组,只有具有背景图像属性的元素,但是,我的代码不工作,我不知道出了什么问题。

elements = document.getElementsByTagName("*")
[].filter.call elements, (el) =>
  if el.currentStyle
    return el.currentStyle['backgroundImage'] isnt 'none'
  else if window.getComputedStyle
    return document.defaultView.getComputedStyle(el,null).getPropertyValue('background-image') isnt 'none'

根据javascript文档,

filter()方法创建一个包含所有通过所提供函数实现的测试的元素的新数组。

所以你需要在使用它之前存储你的过滤数组:

elements = document.getElementsByTagName("*")
filteredElements = [].filter.call elements, (el) =>
  if el.currentStyle
    return el.currentStyle['backgroundImage'] isnt 'none'
  else if window.getComputedStyle
    return document.defaultView.getComputedStyle(el,null).getPropertyValue('background-image') isnt 'none'
// filteredElements is your new array with the filtered elements.