from、includes、indexOf
from、includes、indexOf:https://blog.csdn.net/j59580/article/details/53897630?utm_source=blogxgwz1
语法
Array.from(arrayLike[, mapFn[, thisArg]])
实例
- // Array-like object (arguments) to Array
- function f() {
- return Array.from(arguments);
- }
- f(1, 2, 3);
- // [1, 2, 3]
- // Any iterable object...
- // Set
- var s = new Set(["foo", window]);
- Array.from(s);
- // ["foo", window]
- // Map
- var m = new Map([[1, 2], [2, 4], [4, 8]]);
- Array.from(m);
- // [[1, 2], [2, 4], [4, 8]]
- // String
- Array.from("foo");
- // ["f", "o", "o"]
- // Using an arrow function as the map function to
- // manipulate the elements
- Array.from([1, 2, 3], x => x + x);
- // [2, 4, 6]
- // Generate a sequence of numbers
- Array.from({length: 5}, (v, k) => k);
- // [0, 1, 2, 3, 4]
源码
- // Production steps of ECMA-262, Edition 6, 22.1.2.1
- // Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
- if (!Array.from) {
- Array.from = (function () {
- var toStr = Object.prototype.toString;
- var isCallable = function (fn) {
- return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
- };
- var toInteger = function (value) {
- var number = Number(value);
- if (isNaN(number)) { return 0; }
- if (number === 0 || !isFinite(number)) { return number; }
- return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
- };
- var maxSafeInteger = Math.pow(2, 53) - 1;
- var toLength = function (value) {
- var len = toInteger(value);
- return Math.min(Math.max(len, 0), maxSafeInteger);
- };
- // The length property of the from method is 1.
- return function from(arrayLike/*, mapFn, thisArg */) {
- // 1. Let C be the this value.
- var C = this;
- // 2. Let items be ToObject(arrayLike).
- var items = Object(arrayLike);
- // 3. ReturnIfAbrupt(items).
- if (arrayLike == null) {
- throw new TypeError("Array.from requires an array-like object - not null or undefined");
- }
- // 4. If mapfn is undefined, then let mapping be false.
- var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
- var T;
- if (typeof mapFn !== 'undefined') {
- // 5. else
- // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
- if (!isCallable(mapFn)) {
- throw new TypeError('Array.from: when provided, the second argument must be a function');
- }
- // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
- if (arguments.length > 2) {
- T = arguments[2];
- }
- }
- // 10. Let lenValue be Get(items, "length").
- // 11. Let len be ToLength(lenValue).
- var len = toLength(items.length);
- // 13. If IsConstructor(C) is true, then
- // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
- // 14. a. Else, Let A be ArrayCreate(len).
- var A = isCallable(C) ? Object(new C(len)) : new Array(len);
- // 16. Let k be 0.
- var k = 0;
- // 17. Repeat, while k < len… (also steps a - h)
- var kValue;
- while (k < len) {
- kValue = items[k];
- if (mapFn) {
- A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
- } else {
- A[k] = kValue;
- }
- k += 1;
- }
- // 18. Let putStatus be Put(A, "length", len, true).
- A.length = len;
- // 20. Return A.
- return A;
- };
- }());
- }
includes语法
var boolean = array.includes(searchElement[, fromIndex])
实例
- [1, 2, 3].includes(2); // true
- [1, 2, 3].includes(4); // false
- [1, 2, 3].includes(3, 3); // false
- [1, 2, 3].includes(3, -1); // true
- [1, 2, NaN].includes(NaN); // true
源码
- if (!Array.prototype.includes) {
- Array.prototype.includes = function(searchElement /*, fromIndex*/) {
- 'use strict';
- if (this == null) {
- throw new TypeError('Array.prototype.includes called on null or undefined');
- }
- var O = Object(this);
- var len = parseInt(O.length, 10) || 0;
- if (len === 0) {
- return false;
- }
- var n = parseInt(arguments[1], 10) || 0;
- var k;
- if (n >= 0) {
- k = n;
- } else {
- k = len + n;
- if (k < 0) {k = 0;}
- }
- var currentElement;
- while (k < len) {
- currentElement = O[k];
- if (searchElement === currentElement ||
- (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
- return true;
- }
- k++;
- }
- return false;
- };
- }
indexOf语法
arr.indexOf(searchElement[, fromIndex = 0])
实例
- var array = [2, 9, 9];
- array.indexOf(2); // 0
- array.indexOf(7); // -1
- array.indexOf(9, 2); // 2
- array.indexOf(2, -1); // -1
- array.indexOf(2, -3); // 0
查找元素的所有出现
- var indices = [];
- var array = ['a', 'b', 'a', 'c', 'a', 'd'];
- var element = 'a';
- var idx = array.indexOf(element);
- while (idx != -1) {
- indices.push(idx);
- idx = array.indexOf(element, idx + 1);
- }
- console.log(indices);
- // [0, 2, 4]
查找数组中是否存在元素并更新数组
- function updateVegetablesCollection (veggies, veggie) {
- if (veggies.indexOf(veggie) === -1) {
- veggies.push(veggie);
- console.log('New veggies collection is : ' + veggies);
- } else if (veggies.indexOf(veggie) > -1) {
- console.log(veggie + ' already exists in the veggies collection.');
- }
- }
- var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
- updateVegetablesCollection(veggies, 'spinach');
- // New veggies collection is : potato,tomato,chillies,green-papper,spinach
- updateVegetablesCollection(veggies, 'spinach');
- // spinach already exists in the veggies collection.
源码
- // Production steps of ECMA-262, Edition 5, 15.4.4.14
- // Reference: http://es5.github.io/#x15.4.4.14
- if (!Array.prototype.indexOf) {
- Array.prototype.indexOf = function(searchElement, fromIndex) {
- var k;
- // 1. Let o be the result of calling ToObject passing
- // the this value as the argument.
- if (this == null) {
- throw new TypeError('"this" is null or not defined');
- }
- var o = Object(this);
- // 2. Let lenValue be the result of calling the Get
- // internal method of o with the argument "length".
- // 3. Let len be ToUint32(lenValue).
- var len = o.length >>> 0;
- // 4. If len is 0, return -1.
- if (len === 0) {
- return -1;
- }
- // 5. If argument fromIndex was passed let n be
- // ToInteger(fromIndex); else let n be 0.
- var n = +fromIndex || 0;
- if (Math.abs(n) === Infinity) {
- n = 0;
- }
- // 6. If n >= len, return -1.
- if (n >= len) {
- return -1;
- }
- // 7. If n >= 0, then Let k be n.
- // 8. Else, n<0, Let k be len - abs(n).
- // If k is less than 0, then let k be 0.
- k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
- // 9. Repeat, while k < len
- while (k < len) {
- // a. Let Pk be ToString(k).
- // This is implicit for LHS operands of the in operator
- // b. Let kPresent be the result of calling the
- // HasProperty internal method of o with argument Pk.
- // This step can be combined with c
- // c. If kPresent is true, then
- // i. Let elementK be the result of calling the Get
- // internal method of o with the argument ToString(k).
- // ii. Let same be the result of applying the
- // Strict Equality Comparison Algorithm to
- // searchElement and elementK.
- // iii. If same is true, return k.
- if (k in o && o[k] === searchElement) {
- return k;
- }
- k++;
- }
- return -1;
- };
- }
from、includes、indexOf的更多相关文章
- rails 中 preload、includes、Eager load、Joins 的区别
Rails 提供了四种不同加载关联数据的方法.下面就来介绍一下. 一.Preload Preload 是以附加一条查询语句来加载关联数据的 User.preload(:posts).to_a # =& ...
- indexOf()、includes()、startsWith()、endsWith()
是否包含字符串三种新方法 传统上,JavaScript只有 indexOf 方法,可以用来确定一个字符串是否包含在另一个字符串中.ES6又提供了三种新方法. includes():返回布尔值,表示是否 ...
- find、findIndex、indexOf、lastIndex、includes 数组五种查询条件方法介绍
find() 方法返回数组中满足提供的测试函数的第一个元素的值. 语法: arr.find(callback[, thisArg]) findIndex()方法返回数组中满足提供的测试函数的第一个元素 ...
- JavaScript数组方法--includes、indexOf、lastIndexOf
我们继续吧! includes:includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false.还是先看看includes的用法吧 var ar ...
- indexOf、instanceOf、typeOf、valueOf详解
1.indexOf() 该方法用来返回某个指定的字符串值在字符串中首次出现的位置. 语法:indexOf(searchvalue,fromindex);两个参数,参数一表示查询的字符串值,参数二可选表 ...
- js字符串函数(split、join、indexOf、substring)
1,函数:split()功能:使用一个指定的分隔符把一个字符串分割存储到数组示例: str="jpg|bmp|gif|ico|png";arr= str .split(" ...
- JS数组filter()、map()、some()、every()、forEach()、lastIndexOf()、indexOf()实例
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat=&qu ...
- JavaScript数组方法的兼容性写法 汇总:indexOf()、forEach()、map()、filter()、some()、every()
ECMA Script5中数组方法如indexOf().forEach().map().filter().some()并不支持IE6-8,但是国内依然有一大部分用户使用IE6-8,而以上数组方法又确实 ...
- js中的slice()、substring()、substr()、split()、join()、indexof()
在js中字符截取函数有常用的三个slice().substring().substr()了,下面我来给大家介绍slice().substring().substr()函数在字符截取时的一些用法与区别吧 ...
随机推荐
- 【转载】JDK8 特性 stream(),lambda表达式,
Stream()表达式 虽然大部分情况下stream是容器调用Collection.stream()方法得到的,但stream和collections有以下不同: 无存储.stream不是一种数据结构 ...
- ffmpeg知多少~~~
一.ffmpeg安装: https://jingyan.baidu.com/article/f7ff0bfcd64cea2e26bb1334.html 二.ffmpeg视频处理(包括各种视频流处理 ...
- python基础--匿名函数
def calc(x): return x+1 a=calc(10) print(calc) print(lambda x:x+1)#lambda函数的内存地址,利用函数名可以作为值传递给变量 b=l ...
- (NOIP)CSP-S 2019前计划
前言 无 1.NOIP原题板刷 NOIP原题板刷 这是一篇咕了的blog 2.牛客 & ACwing & 洛谷 网课学习 收获还是蛮大的,不过我没有写博客 3.codeforces专项 ...
- eclipse 报错:One or more constraints have not been satisfied.
接受 我有同样的问题.在我的maven项目中添加速度依赖关系后,我在标记选项卡中得到相同的错误.然后我注意到maven项目创建的web.xml文件具有servlet2.3模式.当我将其更改为servl ...
- 代码片段快捷键 CodeSnippets
CodeSnippets https://github.com/jaydee3/CodeSnippets These are my Xcode 4 CodeSnippets. To use them, ...
- face_recognition开源人脸识别库:离线识别率高达99.38%
基于Python的开源人脸识别库:离线识别率高达99.38%——新开源的用了一下感受一下 原创 2017年07月28日 21:25:28 标签: 人脸识别 / 人脸自动定位 / 人脸识别开源库 / f ...
- 使用代理IP、高匿IP、连接失败
先百度一下,什么是代理IP 我们使用代理IP就是因为某些站点会屏蔽我们的IP,所以我们要动态的更换代理IP. 代理IP: 其中我们首先选择国内的IP,国外的一般都比较慢,其次不要选择如{新疆乌鲁木齐} ...
- Spring Boot 获取 java resources 下文件
Spring Boot 获取 java resources 下文件 Spring Boot 获取 resources 目录下的目录(例:获取 resources 目录下的 template 目录): ...
- 重写hashCode方法,导致内存泄漏
package com.nchu.learn.base.reflect; import org.junit.Test; import java.util.Collection; import java ...