2016-12-01 81 views
1

我正在为我的个人网站构建编辑查看器。我有一个数组,用于收集页面(基于他们的类)中的所有文本框/ textareas。然后通过使用按钮我让用户从编辑移动到编辑。当按下按钮时,我需要遍历“已编辑”对象的数组。JS - 从阵列中删除元素(使用拼接的问题)

使用我在上一个溢出线程中找到的重要提示,我从数组的顶部循环返回。但是,我遇到错误“myFunc error = TypeError:Object不支持属性或方法'拼接'”。我做错了什么?

var editsArray = document.getElementsByClassName("recent_change"); 

    // go backwards through the array 
    for(var i = editsArray.length -1; i >= 0 ; i--){ 
     // check to ensure it is not a 'problem_box' 
     if(editsArray[i].name == 'problem_box'){ 
      // remove that item from array 
      editsArray.splice(i, 1); 
     } 
    } 

我知道,我的收集元素放入数组的方式工作作为我的代码,通过这些编辑重复以前的工作。我现在要回去“清理”收集到我的数组中的内容,并且遇到上述错误。

我不想删除从实际页面收集的对象,我只是想将参考删除到我的阵列外的那些对象。

+5

这不是一个数组;这是一个HTMLCollection。 – 2016-12-01 15:52:57

+2

试试这个►var actualArray = [] .slice.call(editsArray);',取自[这篇文章](http://stackoverflow.com/questions/222841/most-efficient-way-to-convert-an -htmlcollection-to-an-array),然后改变你的代码来处理'actualArray'。这可能会起作用。 – Nope

+3

或新的['Array.from(editsArray)'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)。你也可以使用['.filter()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)。 'editsArray = Array.from(editsArray).filter(function(el){return el.name!='problem_box'})' – 2016-12-01 15:56:37

回答

2
const editsArray = Array.from(document.getElementsByClassName("recent_change")). 
        filter((node) => node.name !== 'problem_box') 

如果您不能使用ES6,请使用Array.prototype.slice替换Array.from,并使用正常函数替换箭头函数。