[英]JavaScript find and remove an element from an array using splice not supported in IE9
I have an array in JavaScript and I need to find a specific element and remove it. 我在JavaScript中有一个数组,我需要找到一个特定的元素并将其删除。 I tried with
splice()
and findIndex()
and it's not supported in JSEclipse nor in IE9. 我尝试了
splice()
和findIndex()
,但JSEclipse和IE9中都不支持它。 I used splice()
and find()
and it doesn't work in IE9. 我使用了
splice()
和find()
,但它在IE9中不起作用。
There are 2 points why my question is not a duplicate: (1) My array is an array of objects so using indexOf()
does not apply. 为什么我的问题不是重复的,有两点:(1)我的数组是一个对象数组,因此使用
indexOf()
不适用。 (2) Support in IE9 is prerequisite for my solutions. (2)IE9支持是我解决方案的先决条件。
I would appreciate any assistant. 我将不胜感激任何助手。
My array: 我的数组:
var portingOptions = [
{
name: 'print',
iconClass: 'faxBlue'
},
{
name: 'pdf',
iconClass: 'pdfBlue'
},
{
name: 'exportToCcr',
iconClass: 'documentBlue'
},
{
name: 'message',
iconClass: 'secureMessageBlue'
},
{
name: 'email',
iconClass: 'emailBlue'
}
];
My code with splice()
and find()
: 我的代码与
splice()
和find()
:
if (myParameters.removeEmailField) {
portingOptions.splice(portingOptions.find(function(element) {
return element.name === 'email';
})
);
}
Does anyone know of a solution that will work on IE9? 有谁知道可以在IE9上使用的解决方案?
You could take a while loop, instead of find
, which is not implemented. 您可以使用while循环,而不是未实现的
find
。
If you like to remove more than one, remove break
statement. 如果要删除多个,请删除
break
语句。
var index = array.length;
while (index--) {
if (array[index].name === 'email') {
array.splice(index, 1);
break;
}
}
You can use jQuery methods $.grep() to replace your Array.find()
您可以使用jQuery方法$ .grep()替换
Array.find()
Array.splice()
instead seems to be supported from IE 5.5 IE 5.5似乎支持
Array.splice()
There is also a nice polyfill that should work on IE9: 还有一个不错的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;
}
}
Ref: https://github.com/jsPolyfill/Array.prototype.find/blob/master/find.js 参考: https : //github.com/jsPolyfill/Array.prototype.find/blob/master/find.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.