【问题标题】:JS - Removing Elements from Array (Issues using Splice)JS - 从数组中删除元素(使用拼接的问题)
【发布时间】:2016-12-01 23:59:01
【问题描述】:

我正在为我的个人网站构建一个编辑查看器。我有一个数组,我用它来收集页面中的所有文本框/文本区域(基于它们的类)。然后通过使用按钮,我让用户从编辑移动到编辑。当按下按钮时,我需要遍历“已编辑”对象的数组。

使用我在之前的溢出线程中找到的重要提示,我从数组顶部循环回了过去。但是,我遇到了错误“myFunc error = TypeError: Object doesn't support property or method 'splice'”的问题。我做错了什么?

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

我知道我将元素收集到数组中的方式有效,因为我的代码迭代这些编辑之前是有效的。我现在要回去“清理”收集到我的数组中的内容,并遇到上述错误。

我不想删除从实际页面收集的对象,我只是想从我的数组中删除对这些对象的 引用

【问题讨论】:

  • 那不是数组;这是一个 HTMLCollection。
  • 试试这个 ► var actualArray = [].slice.call(editsArray); ,取自 this post 然后更改您的代码以处理 actualArray。这可能行得通。
  • 或新的Array.from(editsArray)。你也可以使用.filter()editsArray = Array.from(editsArray).filter(function(el) { return el.name != 'problem_box' })
  • @François Wahl :: 在上述循环的上下文中,这种删除方法真的有效吗?在某些情况下,我们可能需要多次输入该 if 语句。
  • @squint 使用您的建议,我已经完成了这项工作,将变量从“editsArray”重命名为包括“collection”在内的正确名称。 var allEditsArray = Array.from(collectionUnclean).filter(function(el) { return el.name != 'problem_box' }) 执行此操作时出现错误“对象不支持属性或方法'from'”

标签: javascript jquery arrays


【解决方案1】:
const editsArray = Array.from(document.getElementsByClassName("recent_change")).
                     filter((node) => node.name !== 'problem_box')

如果不能使用 ES6,请将 Array.from 替换为 Array.prototype.slice,将箭头函数替换为普通函数。

【讨论】:

    猜你喜欢
    • 2023-01-23
    • 1970-01-01
    • 2010-10-04
    • 2017-04-29
    • 1970-01-01
    • 2015-06-14
    • 2021-11-16
    • 1970-01-01
    • 2019-06-11
    相关资源
    最近更新 更多