Javascript:替代 Array.prototype.find()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25981556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: Alternative to Array.prototype.find()?
提问by bigpotato
I am having an issue where .find()
is not working on my Chrome browser when I use it in AngularJS. This was my original question: AngularJS: Array.prototype.find() does not work in Chrome
我.find()
在 AngularJS 中使用 Chrome 浏览器时遇到问题。这是我最初的问题:AngularJS: Array.prototype.find() 在 Chrome 中不起作用
It's failing on this line:
在这条线上失败了:
console.log($scope.products_colors); // prints `[Object]0: Objectlength: 1__proto__: Array[0]concat: function concat() { [native code] }constructor: function Array() { [native code] }every: function every() { [native code] }filter: function filter() { [native code] }forEach: function forEach() { [native code] }indexOf: function indexOf() { [native code] }join: function join() { [native code] }lastIndexOf: function lastIndexOf() { [native code] }length: 0map: function map() { [native code] }pop: function pop() { [native code] }push: function push() { [native code] }reduce: function reduce() { [native code] }reduceRight: function reduceRight() { [native code] }reverse: function reverse() { [native code] }shift: function shift() { [native code] }slice: function slice() { [native code] }some: function some() { [native code] }sort: function sort() { [native code] }splice: function splice() { [native code] }toLocaleString: function toLocaleString() { [native code] }toString: function toString() { [native code] }unshift: function unshift() { [native code] }__proto__: Object mens_detail_controller.js?body=1:24`
$scope.selected_color = $scope.products_colors.find(function(el) {
return el.id == 91;
});
I know it's failing on .find
, because the code works when I replace it with something else.
我知道它失败了.find
,因为当我用其他东西替换它时代码可以工作。
Is there an alternative to looking through an array and grabbing the first element with a certain condition in javascript?
是否有替代方法可以查看数组并在 javascript 中以特定条件抓取第一个元素?
回答by Matty
回答by Oriol
Here is MDN's polyfill:
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}