JS some()

🌙
手机阅读
本文目录结构

这个 **some()** 方法检测 TypedArray 的一些元素是否通过所提供函数的测试. 这个方法和 Array.prototype.some() 相同. TypedArraytyped array types 之一.

The source for this interactive example is stored in a GitHub repository. If you’d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

语法

typedarray.some(callback[, thisArg])

参数

callback

一个测试每个元素的函数,有3个参数:

currentValue

在typed array中,正在被测试的元素.

index

在typed array中,正在被测试元素的索引.

array

正在被调用的 typed array 本身.

thisArg

可选的. callback  回调函数的 this 值 .

返回值

**true** 如果 callback 函数以任一数组元素为参数调用时,返回 truthy; 否则, **false**.

描述

对于 typed array 中的每个元素,some方法执行一次 callback,直到找到一个callback 返回 true 的元素. 如果一个元素被找到, some 立即返回 true. 否则, some 返回 false.

callback 期望3个参数: 元素的值, 元素的索引, 和被遍历的数组对象.

如果 some 提供 thisArg, 那么thisArg会作为 callback 调用时的this值. 否则, callback 调用时的 thisundefined.  callback 最终可观测的this 是根据  [确定函数this的通常规则] 所确定的.

some 被调用不会改变 typed array .

示例

Testing size of all typed array elements

以下示例测试typed array中的所有元素都大于10.

function isBiggerThan10(element, index, array) {
  return element > 10;
}
new Uint8Array([2, 5, 8, 1, 4]).some(isBiggerThan10); // false
new Uint8Array([12, 5, 8, 1, 4]).some(isBiggerThan10); // true

Testing typed array elements using arrow functions

[Arrow functions] 提供更段的语法做相同的测试.

new Uint8Array([2, 5, 8, 1, 4]).some(elem => elem > 10); // false
new Uint8Array([12, 5, 8, 1, 4]).some(elem => elem > 10); // true

Polyfill

由于没有名为 TypedArray 的全局对象, 必须在“as needed”的基础上进行填充.

// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some
if (!Uint8Array.prototype.some) {
  Object.defineProperty(Uint8Array.prototype, 'some', {
    value: Array.prototype.some
  });
}

假如你需要支持的过时JavaScript引擎不支持[Object.defineProperty],最好不要使用Array.prototype方法填充,因为你不能让它们不可枚举.

标准

Specification Status Comment
[ECMAScript 2015 (6th Edition, ECMA-262)
TypedArray.prototype.some](https://www.ecma-international.org/ecma-262/6.0/#sec-%typedarray%.prototype.some) Standard Initial definition.
[ECMAScript Latest Draft (ECMA-262)
TypedArray.prototype.some](https://tc39.es/ecma262/#sec-%typedarray%.prototype.some) Draft  

浏览器兼容

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Server
Chrome Edge Firefox
some Chrome Full support 45 Edge Full support 14 Firefox Full support 37

Legend

Full support  

Full support

No support  

No support

参阅

AXIHE / 精选资源

浏览全部教程

面试题

学习网站

前端培训
自己甄别

前端书籍

关于朱安邦

我叫 朱安邦,阿西河的站长,在杭州。

以前是一名平面设计师,后来开始接接触前端开发,主要研究前端技术中的JS方向。

业余时间我喜欢分享和交流自己的技术,欢迎大家关注我的 Bilibili

关注我: Github / 知乎

于2021年离开前端领域,目前重心放在研究区块链上面了

我叫朱安邦,阿西河的站长

目前在杭州从事区块链周边的开发工作,机械专业,以前从事平面设计工作。

2014年底脱产在老家自学6个月的前端技术,自学期间几乎从未出过家门,最终找到了满意的前端工作。更多>

于2021年离开前端领域,目前从事区块链方面工作了