这里的问题是您使用的新 JavaScript 语法在 Internet Explorer 或其他旧浏览器中不可用。
正如您所指出的,您可以通过简单地自己定义(“polyfill”)来为 IE 提供缺少的 array.find() 方法。
但您还使用了新的 ES6 语法,destructuring function parameter。
暂时忘记.find(),让我们自己看一下语法问题。这是一个作为独立函数编写的回调版本,用于记录 l 和 r 值,以及一个简单的测试:
// This function actually takes a single argument,
// which is an array of one element. That element is
// an array of two elements which we call l and r.
// We use a destructuring function parameter to get
// those values directly without writing explicit
// code to access the array elements.
var fun = function( [ [l,r] ] ) {
console.log( l, r );
};
fun( [ [12,34] ] ); // Should log: 12 34
sn-p 在支持 ES6 语法的现代浏览器中运行良好,但在任何版本的 IE 中,您都会收到“Expected Identifier”消息,因为它无法识别带有解构参数的新函数语法。
你不能用 polyfill 解决这个问题。这只是在Array 原型中添加了一个缺失的方法,它不会让 IE11 的 JavaScript 版本理解在编写 IE11 时不存在的新语法。
如果您想要 IE 兼容性,您有两种选择。一种是使用 JavaScript 编译器,例如 TypeScript 或 Babel,它可以让您使用这种 ES6 语法并将其转换为 ES5 等价物。这是上述 sn-p 的副本,其代码相同,但启用了 Babel。除了测试之外,我们还将记录我们的 ES6 函数被翻译成的 ES5 源代码:
var fun = function( [ [l,r] ] ) {
console.log( l, r );
};
fun( [ [12,34] ] );
console.log( fun.toString() );
显示的 ES5 代码可能会调用几个名为 _slicedToArray 的辅助函数或其变体。这个函数被 Babel 编译器包含在它生成的代码中。
这在 IE 中运行良好,但需要您开始使用一种或另一种构建过程,以便 Babel 或 TypeScript(或其他)编译器在您进行更改时运行。
另一种选择是编写与 ES5 兼容的代码,您自己进行解构。查看函数的语法以及调用它时传入的内容。该函数实际上接受一个参数,它是一个数组。该数组有一个元素,它也是一个数组。该内部数组有两个元素,为方便起见,您将其命名为 l 和 r。
所以你可以像这样自己做:
// arg is an array of one element.
// That element is itself an array of two elements.
// We call those two elements l and r.
// In ES6, we could use this destructuring syntax:
// function( [ [l,r] ] ) {}
// But for compatibility with ES5, we'll use a single
// function argument containing the outer array, and
// access the l and r values with code.
var fun = function( arg ) {
var l = arg[0][0], r = arg[0][1];
console.log( l, r )
};
fun( [ [12,34] ] );
如果你把这个想法重新插入到你的原始代码中,它也应该在 IE 中工作:
item = totalsArray.find( function( arg ) {
var l = arg[0][0], r = arg[0][1];
return l === a && r === b;
});