【问题标题】:JavaScript find and remove an element from an array using splice not supported in IE9JavaScript 使用 IE9 不支持的拼接从数组中查找和删除元素
【发布时间】:2019-06-11 11:00:41
【问题描述】:

我在 JavaScript 中有一个数组,我需要找到一个特定元素并将其删除。我尝试使用splice()findIndex(),但它在 JSEclipse 和 IE9 中均不受支持。我使用了splice()find(),但它在IE9 中不起作用。

我的问题不重复的原因有两点: (1) 我的数组是一个对象数组,因此使用 indexOf() 不适用。 (2) IE9的支持是我的解决方案的先决条件。

我会很感激任何助手。

我的数组:

var portingOptions = [
   {
      name: 'print',
      iconClass: 'faxBlue'
   },
   {
      name: 'pdf',
      iconClass: 'pdfBlue'
   },
   {
      name: 'exportToCcr',
      iconClass: 'documentBlue'

   },
   {
      name: 'message',
      iconClass: 'secureMessageBlue'
   },
   {
      name: 'email',
      iconClass: 'emailBlue'
   }
];

我的代码与splice()find()

if (myParameters.removeEmailField) {
   portingOptions.splice(portingOptions.find(function(element) {
      return element.name === 'email';
      })
   );
}

有人知道适用于 IE9 的解决方案吗?

【问题讨论】:

标签: javascript arrays internet-explorer-9 array-splice


【解决方案1】:

您可以使用 jQuery 方法 $.grep() 替换您的 Array.find()

Array.splice() 似乎受 IE 5.5 支持

还有一个不错的 polyfill 应该可以在 IE9 上运行:

Array.prototype.find = Array.prototype.find || function(callback) {
  if (this === null) {
    throw new TypeError('Array.prototype.find called on null or undefined');
  } else if (typeof callback !== 'function') {
    throw new TypeError('callback must be a function');
  }
  var list = Object(this);
  // Makes sures is always has an positive integer as length.
  var length = list.length >>> 0;
  var thisArg = arguments[1];
  for (var i = 0; i < length; i++) {
    var element = list[i];
    if ( callback.call(thisArg, element, i, list) ) {
      return element;
    }
  }

参考:https://github.com/jsPolyfill/Array.prototype.find/blob/master/find.js

【讨论】:

  • 我只能用JavaScript,我们的项目没有jQuery。
  • 用 polyfill 更新答案
  • 请仔细阅读我的问题:我尝试使用find(),但IE9不支持。在 JavaScript 中从数组中删除元素不是问题,我的挑战是以 IE9 支持的方式来完成。这是解决方案的条件。
  • 仔细阅读我的回答,如果 Array.find() 不存在,则应用 polyfill 并且您将在 IE9 中也有一个 Array.find()
【解决方案2】:

您可以使用 while 循环,而不是未实现的 find

如果您想删除多个,请删除 break 语句。

var index = array.length;

while (index--) {
    if (array[index].name === 'email') {
        array.splice(index, 1);
        break;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2012-07-16
    • 2022-06-10
    相关资源
    最近更新 更多