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()函数在字符截取时的一些用法与区别吧 ...
随机推荐
- 搭建Eclipse+pydev+python2.7.5+django1.5.1+mysql5.0.45平台
mysqldb 下载地址 http://sourceforge.net/projects/mysql-python/ or https://pypi.python.org/pypi/MySQL-pyt ...
- vue回到顶部
backTop() { var top = document.body.scrollTop || document.documentElement.scrollTop; this.duration - ...
- 详聊js中的原型/原型链
先以一段简单的代码为例: function Dog(params){ this.name = param.name; this.age = param.age; this.ba ...
- mybatis的<用<![CDATA[]] 忽略解析
1 CDATA 术语 CDATA 指的是不应由 XML 解析器进行解析的文本数据(Unparsed Character Data). 在 XML 元素中,"<" 和 &quo ...
- centos下通过conda安装pytorch
一.安装anaconda anaconda安装简单,只要确定自己的系统即可,具体安装请参考这里 二.确定自己的系统版本 我的是centos cat /etc/redhat-release 查看linu ...
- Codeforces Round #340 (Div. 2) E. XOR and Favorite Number (莫队)
题目链接:http://codeforces.com/contest/617/problem/E 题目大意:有n个数和m次查询,每次查询区间[l, r]问满足ai ^ ai+1 ^ ... ^ aj ...
- [NOI1999]生日蛋糕(搜索)
[NOI1999]生日蛋糕 题目背景 7月17日是Mr.W的生日,ACM-THU为此要制作一个体积为Nπ的M层 生日蛋糕,每层都是一个圆柱体. 设从下往上数第i(1<=i<=M)层蛋糕是半 ...
- 切面AOP的切点@Pointcut用法
格式: execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern ...
- window.onload()和$(document).ready的区别( $(document).ready == $(function(){ }) )
首先$(function(){}) 和 $(document).ready(function(){}) 是一个方法,$(function(){})为简写(用的多) $(document).ready和 ...
- Github熟悉一
Code/代码 Commits/提交 Issues/问题 Packages/包装 Marketplace/市场 Topics/话题 Wikis/维基百科 Users/用户 Pull requests/ ...