aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/javascript/reference/global_objects/array/lastindexof/index.html
blob: 930b45d3e32b930309f21112a2dc0aaf8f0f2ac9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
---
title: Array.prototype.lastIndexOf()
slug: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf
tags:
  - Array
  - ECMAScript 5
  - JavaScript
  - Method
  - Prototype
  - polyfill
translation_of: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf
---
<div>{{JSRef}}</div>

<p><code><strong>lastIndexOf()</strong></code> 方法會回傳給定元素於陣列中最後一個被找到之索引,若不存在於陣列中則回傳 -1。搜尋的方向為由陣列尾部向後(即向前)尋找,啟始於 <code>fromIndex</code></p>

<div>{{EmbedInteractiveExample("pages/js/array-lastindexof.html")}}</div>



<h2 id="語法">語法</h2>

<pre class="syntaxbox"><var>arr</var>.lastIndexOf(<var>searchElement</var>)
<var>arr</var>.lastIndexOf(<var>searchElement</var>, <var>fromIndex</var>)
</pre>

<h3 id="參數">參數</h3>

<dl>
 <dt><code>searchElement</code></dt>
 <dd>欲在陣列中搜尋的元素。</dd>
 <dt><code>fromIndex</code> {{optional_inline}}</dt>
 <dd>要由陣列尾部向後(即向前)搜尋的啟始索引。預設為陣列長度減一(<code>arr.length - 1</code>),即會搜尋整個陣列。假如索引大於等於陣列長度,會搜尋整個陣列。如果索引值為負數,會從陣列的最後一個往回算,最後一個的索引值為 -1,以此類推。注意:儘管往回算,但依然會從右往左全部搜尋。如果負數索引值在回頭計算之後仍然小於 0,將會回傳 -1,即不會搜尋陣列。</dd>
</dl>

<h3 id="回傳值">回傳值</h3>

<p>在陣列中找到的最後一個元素索引值;沒找到則為 <strong>-1</strong></p>

<h2 id="描述">描述</h2>

<p><code>lastIndexOf</code> compares <code>searchElement</code> to elements of the Array using <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators">strict equality</a> (the same method used by the ===, or triple-equals, operator).</p>

<h2 id="範例">範例</h2>

<h3 id="使用_lastIndexOf">使用 <code>lastIndexOf</code></h3>

<p>The following example uses <code>lastIndexOf</code> to locate values in an array.</p>

<pre class="brush: js">var numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2);     // 3
numbers.lastIndexOf(7);     // -1
numbers.lastIndexOf(2, 3);  // 3
numbers.lastIndexOf(2, 2);  // 0
numbers.lastIndexOf(2, -2); // 0
numbers.lastIndexOf(2, -1); // 3
</pre>

<h3 id="尋找該元素所有出現在陣列中的位置">尋找該元素所有出現在陣列中的位置</h3>

<p>The following example uses <code>lastIndexOf</code> to find all the indices of an element in a given array, using {{jsxref("Array.prototype.push", "push")}} to add them to another array as they are found.</p>

<pre class="brush: js">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 &gt; 0 ? array.lastIndexOf(element, idx - 1) : -1);
}

console.log(indices);
// [4, 2, 0]
</pre>

<p>Note that we have to handle the case <code>idx == 0</code> separately here because the element will always be found regardless of the <code>fromIndex</code> parameter if it is the first element of the array. This is different from the {{jsxref("Array.prototype.indexOf", "indexOf")}} method.</p>

<h2 id="Polyfill">Polyfill</h2>

<p><code>lastIndexOf</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>lastIndexOf</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, {{jsxref("Number")}}, {{jsxref("Math.floor")}}, {{jsxref("Math.abs")}}, and {{jsxref("Math.min")}} have their original values.</p>

<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.15
// Reference: http://es5.github.io/#x15.4.4.15
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 &gt;&gt;&gt; 0;
    if (len === 0) {
      return -1;
    }

    n = len - 1;
    if (arguments.length &gt; 1) {
      n = Number(arguments[1]);
      if (n != n) {
        n = 0;
      }
      else if (n != 0 &amp;&amp; n != (1 / 0) &amp;&amp; n != -(1 / 0)) {
        n = (n &gt; 0 || -1) * Math.floor(Math.abs(n));
      }
    }

    for (k = n &gt;= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k &gt;= 0; k--) {
      if (k in t &amp;&amp; t[k] === searchElement) {
        return k;
      }
    }
    return -1;
  };
}
</pre>

<p>Again, note that this implementation aims for absolute compatibility with <code>lastIndexOf</code> in Firefox and the SpiderMonkey JavaScript engine, including in several cases which are arguably edge cases. If you intend to use this in real-world applications, you may be able to calculate <code>from</code> with less complicated code if you ignore those cases.</p>

<h2 id="規範">規範</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.4.4.15', 'Array.prototype.lastIndexOf')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition. Implemented in JavaScript 1.6.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="瀏覽器相容性">瀏覽器相容性</h2>

<div>


<p>{{Compat("javascript.builtins.Array.lastIndexOf")}}</p>
</div>

<h2 id="相容性備註">相容性備註</h2>

<ul>
 <li>Starting with Firefox 47 {{geckoRelease(47)}},  this method will no longer return <code>-0</code>. For example, <code>[0].lastIndexOf(0, -0)</code> will now always return <code>+0</code> ({{bug(1242043)}}).</li>
</ul>

<h2 id="參見">參見</h2>

<ul>
 <li>{{jsxref("Array.prototype.indexOf()")}}</li>
 <li>{{jsxref("TypedArray.prototype.lastIndexOf()")}}</li>
</ul>