[英]Javascript: Alternative to Array.prototype.find()?
I am having an issue where .find()
is not working on my Chrome browser when I use it in AngularJS. 我有一个问题,当我在AngularJS中使用它时, .find()
无法在我的Chrome浏览器上运行。 This was my original question: AngularJS: Array.prototype.find() does not work in 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中抓取具有特定条件的第一个元素?
正如elclanrs在评论中指出的那样, xs.filter(f)[0]
可以替代xs.find(f)
。
Here is MDN's polyfill : 这是MDN的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;
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.