作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
最近我发现自己经常使用 ECMA5 提供的新数组方法。我发现它必须经常重复的一项任务是在满足特定条件的数组中找到第一个(或唯一)对象。
您可以使用 Array.some 检查它是否存在,但这只会返回一个 bool 值。相反,我一直在使用 Array.filter,但这不如循环有效,因为它不会在找到项目时停止。有没有我错过的方法可以破解成我想要的东西?
var things = [
{name: "house"},
{name: "table"},
{name: "egg"},
{name: "bob"},
{name: "hamster"}
];
var getBob = function(thing){
return thing && thing.name == "bob";
};
// returns true not the object i want
console.log(things.some(getBob));
// returns the object but in an array and does not break when found
console.log(things.filter(getBob)[0]);
最佳答案
ES5 中没有内置方法。
ES6 为此 http://people.mozilla.org/~jorendorff/es6-draft.html#sec-22.1.3.8 添加了 Array.prototype.find
console.log(things.find(getBob));
这是一个改编自 https://gist.github.com/dcherman/5167353 的 polyfill
(function() {
function polyfill(fnName) {
if (!Array.prototype[fnName]) {
Object.defineProperty(Array.prototype, fnName, {
value: function( predicate /*, thisArg */ ) {
var i, len, test, thisArg = arguments[ 1 ];
if ( typeof predicate !== "function" ) {
throw new TypeError();
}
test = !thisArg ? predicate : function() {
return predicate.apply( thisArg, arguments );
};
for( i = 0, len = this.length; i < len; i++ ) {
if ( test(this[i], i, this) === true ) {
return fnName === "find" ? this[ i ] : i;
}
}
if ( fnName !== "find" ) {
return -1;
}
},
enumerable: false,
writable: true,
configurable: true
});
}
}
[ 'find', 'findIndex' ].forEach(function(method) {
polyfill(method);
});
}());
我还没有检查它是否符合草案。
关于javascript - ECMA5 数组方法 - 查找数组中同类的第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18773212/
所以我有这个 UltraTicTacToe 游戏,我正在用 HTML/CSS/JS 编码。它由表中表中的表组成。当您单击 X 或 O 时,我想要突出显示您应该进入的下一个 TicTacToe 牌 ta
Some text Some more text 如何让每个 .example 的 .whatever 包含其 .test 的内容? 例如,如果代码是这样的: Som
我是一名优秀的程序员,十分优秀!