lastIndexOf、map

来源:互联网 发布:人工智能老师 编辑:程序博客网 时间:2024/05/23 00:01
语法
arr.lastIndexOf(searchElement[, fromIndex = arr.length - 1])


实例

var array = [2, 5, 9, 2];array.lastIndexOf(2);     // 3array.lastIndexOf(7);     // -1array.lastIndexOf(2, 3);  // 3array.lastIndexOf(2, 2);  // 0array.lastIndexOf(2, -2); // 0array.lastIndexOf(2, -1); // 3

查找元素的所有出现

var indices = [];var array = ['a', 'b', 'a', 'c', 'a', 'd'];var element = 'a';var idx = array.lastIndexOf(element);while (idx != -1) {  indices.push(idx);  idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1);}console.log(indices);// [4, 2, 0]

源码

// Production steps of ECMA-262, Edition 5, 15.4.4.15// Reference: http://es5.github.io/#x15.4.4.15if (!Array.prototype.lastIndexOf) {  Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {    'use strict';    if (this === void 0 || this === null) {      throw new TypeError();    }    var n, k,      t = Object(this),      len = t.length >>> 0;    if (len === 0) {      return -1;    }    n = len - 1;    if (arguments.length > 1) {      n = Number(arguments[1]);      if (n != n) {        n = 0;      }      else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {        n = (n > 0 || -1) * Math.floor(Math.abs(n));      }    }    for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) {      if (k in t && t[k] === searchElement) {        return k;      }    }    return -1;  };}

length语法
arr.length

实例

var numbers = [1, 2, 3, 4, 5];for (var i = 0; i < numbers.length; i++) {  numbers[i] *= 2;}// numbers is now [2, 4, 6, 8, 10]

设置长度

if (statesUS.length > 50) {  statesUS.length = 50;}

map语法

arr.map(callback[, thisArg])

实例

var numbers = [1, 4, 9];var roots = numbers.map(Math.sqrt);// roots is now [1, 2, 3], numbers is still [1, 4, 9]

使用map来格式化对象数组

var kvArray = [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}];var reformattedArray = kvArray.map(function(obj){    var rObj = {};   rObj[obj.key] = obj.value;   return rObj;});// reformattedArray is now [{1:10}, {2:20}, {3:30}], // kvArray is still [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}]


使用包含参数的函数映射数字数组
var numbers = [1, 4, 9];var doubles = numbers.map(function(num) {  return num * 2;});// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]

一般使用方法
var map = Array.prototype.map;var a = map.call('Hello World', function(x) { return x.charCodeAt(0); });// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

倒序

var str = '12345';Array.prototype.map.call(str, function(x) {  return x;}).reverse().join(''); // Output: '54321'// Bonus: use '===' to test if original string was a palindrome

巧妙的使用案例
// Consider:['1', '2', '3'].map(parseInt);// While one could expect [1, 2, 3]// The actual result is [1, NaN, NaN]// parseInt is often used with one argument, but takes two.// The first is an expression and the second is the radix.// To the callback function, Array.prototype.map passes 3 arguments: // the element, the index, the array// The third argument is ignored by parseInt, but not the second one,// hence the possible confusion. See the blog post for more detailsfunction returnInt(element) {  return parseInt(element, 10);}['1', '2', '3'].map(returnInt); // [1, 2, 3]// Actual result is an array of numbers (as expected)// A simpler way to achieve the above, while avoiding the "gotcha":['1', '2', '3'].map(Number); // [1, 2, 3]


源码
// Production steps of ECMA-262, Edition 5, 15.4.4.19// Reference: http://es5.github.io/#x15.4.4.19if (!Array.prototype.map) {  Array.prototype.map = function(callback, thisArg) {    var T, A, k;    if (this == null) {      throw new TypeError(' this is null or not defined');    }    // 1. Let O be the result of calling ToObject passing the |this|     //    value as the argument.    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 IsCallable(callback) is false, throw a TypeError exception.    // See: http://es5.github.com/#x9.11    if (typeof callback !== 'function') {      throw new TypeError(callback + ' is not a function');    }    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.    if (arguments.length > 1) {      T = thisArg;    }    // 6. Let A be a new array created as if by the expression new Array(len)     //    where Array is the standard built-in constructor with that name and     //    len is the value of len.    A = new Array(len);    // 7. Let k be 0    k = 0;    // 8. Repeat, while k < len    while (k < len) {      var kValue, mappedValue;      // 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      if (k in O) {        // i. Let kValue be the result of calling the Get internal         //    method of O with argument Pk.        kValue = O[k];        // ii. Let mappedValue be the result of calling the Call internal         //     method of callback with T as the this value and argument         //     list containing kValue, k, and O.        mappedValue = callback.call(T, kValue, k, O);        // iii. Call the DefineOwnProperty internal method of A with arguments        // Pk, Property Descriptor        // { Value: mappedValue,        //   Writable: true,        //   Enumerable: true,        //   Configurable: true },        // and false.        // In browsers that support Object.defineProperty, use the following:        // Object.defineProperty(A, k, {        //   value: mappedValue,        //   writable: true,        //   enumerable: true,        //   configurable: true        // });        // For best browser support, use the following:        A[k] = mappedValue;      }      // d. Increase k by 1.      k++;    }    // 9. return A    return A;  };}




0 0
原创粉丝点击