[英]JavaScript find and remove an element from an array using splice not supported in IE9
我在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上使用的解决方案?
您可以使用while循环,而不是未实现的find
。
如果要删除多个,请删除break
语句。
var index = array.length;
while (index--) {
if (array[index].name === 'email') {
array.splice(index, 1);
break;
}
}
您可以使用jQuery方法$ .grep()替换Array.find()
IE 5.5似乎支持Array.splice()
还有一个不错的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.