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()函数在字符截取时的一些用法与区别吧 ...
随机推荐
- github(1):
1.目的:借助github托管项目带按摩 2.仓库:创建一个Repository 3.收藏(Start):仓库主页start按钮,意思是收藏项目的人数,在github上如果有一个项目获得100个sta ...
- Sublime Text插件安装方法和常用插件
插件安装方法: 1.打开Sublime Text,按下Ctrl+Shift+P调出命令面板 ; 2.输入install 调出 Install Package Control选项并回车; 3.再次按下C ...
- Docker实战部署应用——Redis
Redis 部署 拉取Redis镜像 docker pull redis 创建Redis容器 docker run -id --name=sun_redis -p 6379:6379 redis 客户 ...
- Install.php
<!DOCTYPE html><html lang="en"><head> <meta charset="utf-8" ...
- Python单例模式的设计与实现【完美版】
目录 1. 按 2. 本文地址 3. 通过继承单例父类来实现 4. 使用装饰器实现 4.1. 懒汉式 4.2. 饿汉式 4.2.1. 未加锁版 4.2.2. 加锁版 1. 按 众所周知,对象是解决继承 ...
- [Usaco2007 Jan]Telephone Lines架设电话线(最短路,二分)
[Usaco2007 Jan]Telephone Lines架设电话线 Description FarmerJohn打算将电话线引到自己的农场,但电信公司并不打算为他提供免费服务.于是,FJ必须为此向 ...
- JVM的内存区域划分(jdk7和jdk8)
参考: https://blog.csdn.net/l1394049664/article/details/81486470?tdsourcetag=s_pctim_aiomsg https://bl ...
- Test 6.23 T1 扫雷
题目背景 题目描述 输入格式 输出格式 样例输入输出 数据范围 解析 我们设两个作弊器的参数分别为\((a_1,b_1)\)和\((a_2,b_2)\),那么设 \[ S1=\frac{a_1}{b_ ...
- git本地创建一个分支并上传到远程服务器上
git branch 查看分支 新建分支:git checkout -b dev 把新建的本地分支push到远程服务器 git push origin 本地名字:外地名字 删除远程分支 git pus ...
- 进入cmd的另外的一种方式
按Shift键+鼠标右键 进入powershell ,进入的界面和普通的shell界面不一样