概念
Array.prototype.some方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。
语法
arr.some(callback(element[, index[, array]])[, thisArg])
参数
callback
用来测试每个元素的函数,接受三个参数:element
数组中正在处理的元素。index 可选
数组中正在处理的元素的索引值。array 可选
被调用的数组。
*thisArg 可选
执行 callback 时使用的 this 值。
返回值
result
数组中有至少一个元素通过回调函数的测试就会返回true;所有元素都没有通过回调函数的测试返回值才会为false。
描述
some() 为数组中的每一个元素执行一次 callback 函数,直到找到一个使得 callback 返回一个“真值”(即可转换为布尔值 true 的值)。如果找到了这样一个值,some() 将会立即返回 true。否则,some() 返回 false。
callback 只会在那些”有值“的索引上被调用,不会在那些被删除或从来未被赋值的索引上调用。
callback 被调用时传入三个参数:元素的值,元素的索引,被遍历的数组。
如果一个thisArg参数提供给some(),它将被用作调用的 callback的 this 值。否则, 它的 this value将是 undefined。this的值最终通过callback来观察,根据 the usual rules for determining the this seen by a function的this判定规则来确定。
some() 被调用时不会改变数组。
some() 遍历的元素的范围在第一次调用 callback. 前就已经确定了。在调用 some() 后被添加到数组中的值不会被 callback 访问到。
如果数组中存在且还未被访问到的元素被 callback 改变了,则其传递给 callback 的值是 some() 访问到它那一刻的值。已经被删除的元素不会被访问到。
例子
例一、检查数组是否有大于10的元素
1[1, 11, 9, 5, 8].some(function(item, index) {
2 console.log(item, index);
3 // => 1, 0
4 // => 11, 1
5 return item > 10;
6});
7// => true
8
9// 缩写
10[1, 11, 9, 5, 8].some(item=>item>10); // => true
例二、空数组调用some方法
1[].some(item=>item);
2// => false
3
4[].some(item=>!item);
5// => false
例三、用some实现flat方法
1let arr = ['a', ['b', 'c', ['d', 'e', 'f', ['g']]]];
2function flat(array){
3 while (array.some(Array.isArray)) {
4 array = [].concat(...array);
5 }
6 return array;
7}
8flat(arr);
9// => ['a', 'b', 'c', 'd', 'e', 'f', 'g']
面试题
一、请写出下面的运行结果?
1[].some(item=>!item); // => ???
2[null].some(item=>!item); // => ???
3['a', 'b', 'c'].some(item=> item.charCodeAt()> 100); // => ???
Polyfill
1if (!Array.prototype.some) {
2 Array.prototype.some = function(fun /*, thisArg*/ ) {
3 'use strict';
4 if (this == null) {
5 throw new TypeError('Array.prototype.some called on null or undefined');
6 }
7 if (typeof fun !== 'function') {
8 throw new TypeError();
9 }
10 var t = Object(this);
11 var len = t.length >>> 0;
12 var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
13 for (var i = 0; i < len; i++) {
14 if (i in t && fun.call(thisArg, t[i], i, t)) {
15 return true;
16 }
17 }
18 return false;
19 };
20}
相关文章
Array中slice介绍
Array中join介绍
不是你记忆中的join,但致命的程度没两样
前端咖,值得关注,在看哦