“对象不支持IE中的属性或方法'find'”
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了“对象不支持IE中的属性或方法'find'”相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
var data = [{
"Id": "SWE",
"Country": "Sweden",
"Population": 9592552
}, {
"Id": "NOR",
"Country": "Norway",
"Population": 5084190
}];
function display(e) {
alert("E" + e);
var countryData = data.find(function (element, index, array) {
return element.Id === e;
});
alert(countryData.Population);
}
display('SWE');
});
</script>
</head>
</html>
上面发布的代码在Firefox和Chrome上正常运行,但我在Internet Explorer中收到错误。错误信息:
Object doesn't support property or method 'find'
您正在使用javascript array.find()
方法。请注意,这是标准的JS,与jQuery无关。实际上,问题中的整个代码根本不使用jQuery。
你可以在这里找到array.find()
的文档:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find
如果您滚动到此页面的底部,您将注意到它具有浏览器支持信息,您将看到它表明IE不支持此方法。
具有讽刺意味的是,你最好的方法是使用jQuery,它具有所有浏览器都支持的类似功能。
如上所述,IE中不支持array.find()
。
但是,您可以在此处阅读有关Polyfill的信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Polyfill
此方法已添加到ECMAScript 2015规范中,可能尚未在所有JavaScript实现中提供。但是,您可以使用以下代码段对Array.prototype.find进行填充:
码:
// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function(predicate) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
// d. If testResult is true, return kValue.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
// e. Increase k by 1.
k++;
}
// 7. Return undefined.
return undefined;
}
});
}
任何版本的IE都不支持Array.prototype.find
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
这是一个解决方法。您可以使用filter而不是find;但过滤器返回匹配对象的数组。 find
只返回数组中的第一个匹配项。那么,为什么不使用过滤器如下;
data.filter(function (x) {
return x.Id === e
})[0];
对于微软浏览器的Array.find
方法支持始于Edge。
W3Schools compatibility table表示支持从版本12开始,而Can I Use compatibility table表示版本12和14之间的支持未知,从版本15开始正式支持。
以上是关于“对象不支持IE中的属性或方法'find'”的主要内容,如果未能解决你的问题,请参考以下文章