DIV CSS 佈局教程網

lastIndexOf() 的第二個參數:陣列與字串反向搜尋的進階用法
編輯:JavaScript基礎知識     

Array.prototype.lastIndexOf 與 String.prototype.lastIndexOf 是非常實用的方法,不過很多人不知道它其實可以傳遞兩個參數,第二個參數決定了搜尋的起始位置。

語法

str.lastIndexOf(searchValue[, fromIndex])

lastIndexOf() 回傳指定值在呼叫該方法的字串中最後出現的位置,找不到則回傳 -1。它從字串尾端向前查找,起點由 fromIndex 決定。

參數:

1、searchValue:一個字串,表示被查找的值。
2、fromIndex:从此位置開始向前查找,可為任意整數,預設值為 str.length。若為負值則視為 0;若 fromIndex 大於 str.length,則視為 str.length。

它區分大小寫

"Blue Whale, Killer Whale".lastIndexOf("blue");   //回傳 -1

陣列上的用法

//建立一個陣列
var ar = ["ab", "cd", "ef", "ab", "cd"];

//找到最後一個 cd 的位置
document.write(ar.lastIndexOf("cd") + "<br/>");     //輸出: 4

//從正數第 2 個位置往前搜,找最後一個 cd
document.write(ar.lastIndexOf("cd", 2) + "<br/>");   //輸出: 1

//從倒數第 3 個往前搜,找最後一個 ab
document.write(ar.lastIndexOf("ab", -3) + "<br/>");  //輸出: 0

字串上的用法完全類似:

"canal".lastIndexOf("a");     //回傳 3
"canal".lastIndexOf("a", 2);   //回傳 1
"canal".lastIndexOf("a", 0);   //回傳 -1,從第 0 個往前搜,不存在 'a'
"canal".lastIndexOf("x");      //回傳 -1

IE8 及以下的相容實作

微軟的 IE8 及更舊版本不支援 Array.lastIndexOf,需要補一段 polyfill:

if (!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;
  };
}

也可以直接引入 ES5-Slim 讓舊版瀏覽器完整相容 ES5 語法。

為什麼要盡量避免 for-in

在 Array.prototype 上附加方法後,for-in 會把 lastIndexOf 也列舉出來:

for (var idx in [1, 3, 5, 7, 9]) {
  console.log(idx)
}
>> 0 1 2 3 4 lastIndexOf

應該改用傳統的 for 迴圈:

for (var idx = 0; idx < [1, 3, 5, 7, 9].length; idx++) {
  console.log(idx)
}

若要解決列舉問題,可以用 Object.defineProperty 把 enumerable 設為 false:

Object.defineProperty(Array, "lastIndexOf", { enumerable: false })

但諷刺的是,需要 polyfill 的那些瀏覽器往往根本不支援 defineProperty。而且在多數瀏覽器上 for-in 都比 for 迴圈慢很多,因此應盡量避免 for-in。

那要怎麼列舉物件的 key 呢?用 Object.keys({ a: 1 }) 就能拿到 key 的陣列。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved