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 搭建博客,出现 hexo g -d 报错
想搭建一个个人博客,但是在将博客推送到Github上的时候在git bash 下运行hexo g -d命令出现错误: 错误如下: fatal: HttpRequestException encoun ...
- 使用vue-resource请求数据的步骤
1.需要安装 vue-resource模块 注意加上--save npm install vue-resource --save 2.main.js 引入vue-resource import Vue ...
- break语句、continue语句、goto语句的用法辨析
1.break语句 break语句常使用在switch语句.循环体以及if语句中,它的作用是跳出循环,而且只能跳出一层循环. for (i = 0; i < 10; ++j) { for (j ...
- CreateProcessAsUser 服务调用
CreateProcessAsUser 函数 如果想通过服务向桌面用户Session 创建一个复杂UI 程序界面,则需要使用CreateProcessAsUser 函数为用户创建一个新进程用来运行相应 ...
- 2018-08-15-weekly
Algorithm 5. Longest Palindromic Substring What 给定一个字符串s,找到s中最长的回文子字符串. 给定s的最大长度为1000. How 这是一道比较经典的 ...
- [python 学习] IO操作之读写文件
一.读取全部文件: # -*- coding: utf-8 -*- f = open('qq_url.txt','r'); print f.read(); f.close(); 二.读取规定长度文件 ...
- tpcc-mysql测试mysql5.6 (EXT4文件系统)
操作系统版本:CentOS release 6.5 (Final) 2.6.32-431.el6.x86_64 #1 内存:32G CPU:Intel(R) Xeon(R) CPU E5-2450 ...
- UVa 1009 Sharing Chocolate (数位dp)
题目链接: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_proble ...
- JMeter-性能测试之报表设定的注意事项
在使用 Jmeter 执行性能测试时,需要屏蔽以下模块: 结果树 图形结果 断言 具体的说明,可以见官网:http://jmeter.apache.org/usermanual/component_r ...
- 帝国CMS编辑器粘贴Word图片
图片的复制无非有两种方法,一种是图片直接上传到服务器,另外一种转换成二进制流的base64码 目前限chrome浏览器使用,但是项目要求需要支持所有的浏览器,包括Windows和macOS系统.没有办 ...