【问题标题】:coffeescript - Array filtering not workingcoffeescript - 数组过滤不起作用
【发布时间】:2025-12-20 10:30:11
【问题描述】:

我正在尝试获取一个仅包含具有 background-image 属性的元素的数组,但是,我的代码不起作用,我不确定出了什么问题。

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'

【问题讨论】:

  • 如何“它不起作用”?你在哪个页面上应用它?预期的结果是什么,会发生什么?
  • 如果我在过滤器调用之前和之后注销元素,结果是一样的。
  • 哦,你期待什么,你没有在任何地方返回过滤后的数组,试试这样 -> jsfiddle.net/adeneo/Rqd22
  • @EvanWard:filter 不会改变elements。它确实返回了一个新数组。

标签: javascript arrays coffeescript filtering


【解决方案1】:

根据javascript documentation

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.

【讨论】: