aboutsummaryrefslogtreecommitdiff
path: root/files/vi/web/javascript/reference/global_objects/array/find/index.html
blob: ba4631a92462269f3891ca875a6d51f8abb59cc2 (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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
---
title: Array.prototype.find()
slug: Web/JavaScript/Reference/Global_Objects/Array/find
translation_of: Web/JavaScript/Reference/Global_Objects/Array/find
---
<div>{{JSRef}}</div>

<p>Phương thức <code><strong>find() </strong></code>sẽ trả về <strong>giá trị đầu tiên tìm thấy</strong> ở trong mảng được cung cấp. Hoặc có thể trả về {{jsxref("undefined")}} .</p>

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



<p>Xem thêm phương thức {{jsxref("Array.findIndex", "findIndex()")}} , sẽ trả về <strong>index</strong> của phần tử tìm thấy trong mảng thay vì giá trị của nó.</p>

<p>Nếu bạn muốn tìm vị trí của phần tử hoặc tìm phần tử đó có tồn tại trong mảng hay không, hãy thử sử dụng  {{jsxref("Array.prototype.indexOf()")}} or {{jsxref("Array.prototype.includes()")}}.</p>

<h2 id="Cú_Pháp">Cú Pháp</h2>

<pre class="syntaxbox"><var>arr</var>.find(<var>callback(element[, index[, array]])</var>[, <var>thisArg</var>])</pre>

<h3 id="Parameters_(_thông_số_đầu_vào_)">Parameters ( thông số đầu vào )</h3>

<dl>
 <dt><code>callback</code></dt>
 <dd>Hàm thực thi với mỗi giá trị trong mảng, chuyền vào 3 giá trị :
 <dl>
  <dt><code>element</code></dt>
  <dd>Phần tử hiện tại đang được xử lý trong mảng.</dd>
  <dt><code>index</code> {{optional_inline}}</dt>
  <dd>Thứ tự của phần tử hiện tại đang được xử lý trong mảng..</dd>
  <dt><code>array</code> {{optional_inline}}</dt>
  <dd>Mảng được gọi.</dd>
 </dl>
 </dd>
 <dt><code>thisArg</code> {{optional_inline}}</dt>
 <dd>Đối tượng tùy chọn để sử dụng như thế này khi thực hiện <code>callback</code>.</dd>
</dl>

<h3 id="Return_value_(_giá_trị_trả_về_)">Return value ( giá trị trả về )</h3>

<p><strong>Giá trị ( value )</strong> của<strong> phần tử đầu tiên ( first element )</strong> trong mảng thỏa mãn chức năng kiểm tra được cung cấp. Nếu không, sẽ trả về {{jsxref("undefined")}}.</p>

<h2 id="Mô_Tả">Mô Tả</h2>

<p>Phương thức <code>find thực thi hàm</code>  <code>callback</code> với mỗi giá trị trong mảng cho đến khi tìm được giá trị mà hàm <code>callback</code> trả về giá trị. Nếu phần tử đó được tìm thấy, phương thức <code>find sẽ</code> trả về giá trị của phần tử đó. Nếu không tìm thấy, <code>find</code> sẽ trả về {{jsxref("undefined")}}. <code>callback</code> được gọi cho mọi <code>index</code> có trong mảng từ <code>0</code> đến<code>length - 1</code> và cho tất cả các <code>indexes</code>, không chỉ những giá trị đã được gán. Điều này chỉ ra rằng nó có thể kém hiệu quả hơn so với các phương thức khác chỉ truy cập các <code>indexes</code> có giá trị được gán.</p>

<p><code>callback</code> được gọi với ba <strong>arguments</strong>: giá trị của phần tử ( the value of the element ), biến đếm của phần tử ( the index of the element ) và đối tượng mảng cần tìm ( the Array object being traversed ).</p>

<p>Nếu <code>thisArg</code> tham số ( <strong>parameter </strong>) cung cấp cho phương thức <code>find</code>, nó sẽ được sử dụng như là giá trị <code>this</code> cho mỗi lần gọi <code>callback</code>. Nếu không được cung cấp tham số, thì {{jsxref("undefined")}} sẽ được thay thế.</p>

<p>Phương thức <code>find</code> sẽ không làm thay đổi mảng mà nó được gọi hoặc sử dụng.</p>

<p>Phạm vi của các phần tử được xử lý bởi <code>find</code> sẽ được gán trước ghi gọi hàm <code>callback</code>. Vì thế, <code>callback</code> sẽ không truy cập các phần tử được gắn vào mảng sau khi phương thức <code>find được</code> bắt đầu. Các phần tử bị xóa vẫn có thể truy cập được.</p>

<h2 id="Ví_Dụ">Ví Dụ</h2>

<h3 id="Tìm_một_đối_tượng_trong_một_mảng_bằng_một_trong_các_thuộc_tính">Tìm một đối tượng trong một mảng bằng một trong các thuộc tính</h3>

<pre class="brush: js">const inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function isCherries(fruit) {
    return fruit.name === 'cherries';
}

console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }</pre>

<h4 id="Sử_dụng_arrow_function_(_ES2015_)">Sử dụng arrow function ( ES2015 )</h4>

<pre class="brush: js">const inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

const result = inventory.find( fruit =&gt; fruit.name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }</pre>

<h3 id="Tìm_số_nguyên_tố_trong_mảng">Tìm số nguyên tố trong mảng</h3>

<p>Theo ví dụ sau đây tìm thấy một phần tử trong mảng là số nguyên tố (hoặc sẽ trả về {{jsxref("undefined")}} nếu trong mảng không có số nguyên tố nào).</p>

<pre class="brush: js">function isPrime(element, index, array) {
  let start = 2;
  while (start &lt;= Math.sqrt(element)) {
    if (element % start++ &lt; 1) {
      return false;
    }
  }
  return element &gt; 1;
}

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5
</pre>

<p>Ví dụ sau đây cho thấy các phần tử không tồn tại và bị xóa vẫn được truy cập và giá trị được chuyển cho <code>callback </code>lại là giá trị của chúng khi được truy cập.</p>

<pre class="brush: js">// Declare array with no element at index 2, 3 and 4
const array = [0,1,,,,5,6];

// Shows all indexes, not just those that have been assigned values
array.find(function(value, index) {
  console.log('Visited index ' + index + ' with value ' + value);
});

// Shows all indexes, including deleted
array.find(function(value, index) {

  // Delete element 5 on first iteration
  if (index == 0) {
    console.log('Deleting array[5] with value ' + array[5]);
    delete array[5];
  }
  // Element 5 is still visited even though deleted
  console.log('Visited index ' + index + ' with value ' + value);
});
// expected output:
// Deleting array[5] with value 5
// Visited index 0 with value 0
// Visited index 1 with value 1
// Visited index 2 with value undefined
// Visited index 3 with value undefined
// Visited index 4 with value undefined
// Visited index 5 with value undefined
// Visited index 6 with value 6
</pre>

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

<p>Phương pháp này đã được thêm vào ECMAScript 2015 và có thể không có sẵn trong tất cả các phiên bản JavaScript. Tuy nhiên, bạn có thể sử dụng <code>Array.prototype.find</code> với cú pháp :</p>

<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    value: function(predicate) {
     // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length &gt;&gt;&gt; 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k &lt; len
      while (k &lt; len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return kValue.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return kValue;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return undefined.
      return undefined;
    },
    configurable: true,
    writable: true
  });
}

</pre>

<h2 id="Đặc_Điểm">Đặc Điểm</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('ES2015', '#sec-array.prototype.find', 'Array.prototype.find')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Tính_Tương_Thích_Với_Trình_Duyệt_Web">Tính Tương Thích Với Trình Duyệt Web</h2>

<div>


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

<h2 id="Những_Phương_Thức_Liên_Quan">Những Phương Thức Liên Quan</h2>

<ul>
 <li>{{jsxref("Array.prototype.findIndex()")}} – find and return an index</li>
 <li>{{jsxref("Array.prototype.includes()")}} – test whether a value exists in the array</li>
 <li>{{jsxref("Array.prototype.filter()")}} – find all matching elements</li>
 <li>{{jsxref("Array.prototype.every()")}} – test all elements together</li>
 <li>{{jsxref("Array.prototype.some()")}} – test at least one element</li>
</ul>