Vanilla Javascript 相当于 lodash _.includes
Vanilla Javascript equivalent for lodash _.includes
我正在使用 lodash includes
函数来检查数组中是否存在目标值...
_.includes(array, target)
并希望在 ES5(或 ES6)中找到一个好的等价物
我错过了什么吗?没有 ES5 Array.prototype 等价物吗?
或者我唯一的选择是使用 indexOf
?
ES7: Array.prototype.includes()
[1, 2, 3].includes(2); // true
ES5: Array.prototype.indexOf()
>= 0
[2, 5, 9].indexOf(5) >= 0; // true
[2, 5, 9].indexOf(7) >= 0; // false
如果您更喜欢函数:
function includes (array, element) { return array.indexOf(element) >= 0 }
并将其用作:
includes([2, 5, 9], 5); // true
我正在使用 lodash includes
函数来检查数组中是否存在目标值...
_.includes(array, target)
并希望在 ES5(或 ES6)中找到一个好的等价物
我错过了什么吗?没有 ES5 Array.prototype 等价物吗?
或者我唯一的选择是使用 indexOf
?
ES7: Array.prototype.includes()
[1, 2, 3].includes(2); // true
ES5: Array.prototype.indexOf()
>= 0
[2, 5, 9].indexOf(5) >= 0; // true
[2, 5, 9].indexOf(7) >= 0; // false
如果您更喜欢函数:
function includes (array, element) { return array.indexOf(element) >= 0 }
并将其用作:
includes([2, 5, 9], 5); // true