|
4 | 4 | * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} |
5 | 5 | */ |
6 | 6 |
|
| 7 | +var SafeRange = require('./SafeRange'); |
| 8 | + |
7 | 9 | /** |
8 | | - * Returns the first element from the array which optionally has a property matching the given value. |
| 10 | + * Returns the first element in the array. |
| 11 | + * |
| 12 | + * You can optionally specify a matching criteria using the `property` and `value` arguments. |
| 13 | + * |
| 14 | + * For example: `getAll('visible', true)` would return the first element that had its `visible` property set. |
9 | 15 | * |
10 | | - * @function Phaser.Utils.Array.GetFirstElement |
| 16 | + * Optionally you can specify a start and end index. For example if the array had 100 elements, |
| 17 | + * and you set `startIndex` to 0 and `endIndex` to 50, it would search only the first 50 elements. |
| 18 | + * |
| 19 | + * @function Phaser.Utils.Array.GetFirst |
11 | 20 | * @since 3.4.0 |
12 | 21 | * |
13 | 22 | * @param {array} array - The array to search. |
14 | | - * @param {string} property - The property to test on each array element. |
15 | | - * @param {*} value - The value to test the property against. Must pass a strict (`===`) comparison check. |
| 23 | + * @param {string} [property] - The property to test on each array element. |
| 24 | + * @param {*} [value] - The value to test the property against. Must pass a strict (`===`) comparison check. |
16 | 25 | * @param {integer} [startIndex=0] - An optional start index to search from. |
17 | 26 | * @param {integer} [endIndex=array.length] - An optional end index to search up to (but not included) |
18 | 27 | * |
19 | 28 | * @return {object} The first matching element from the array, or `null` if no element could be found in the range given. |
20 | 29 | */ |
21 | | -var GetFirstElement = function (array, property, value, startIndex, endIndex) |
| 30 | +var GetFirst = function (array, property, value, startIndex, endIndex) |
22 | 31 | { |
23 | 32 | if (startIndex === undefined) { startIndex = 0; } |
24 | 33 | if (endIndex === undefined) { endIndex = array.length; } |
25 | 34 |
|
26 | | - for (var i = startIndex; i < endIndex; i++) |
| 35 | + if (SafeRange(array, startIndex, endIndex)) |
27 | 36 | { |
28 | | - var child = array[i]; |
29 | | - |
30 | | - if (!property || child[property] === value) |
| 37 | + for (var i = startIndex; i < endIndex; i++) |
31 | 38 | { |
32 | | - return child; |
| 39 | + var child = array[i]; |
| 40 | + |
| 41 | + if (!property || |
| 42 | + (property && value === undefined && child.hasOwnProperty(property)) || |
| 43 | + (property && value !== undefined && child[property] === value)) |
| 44 | + { |
| 45 | + return child; |
| 46 | + } |
33 | 47 | } |
34 | 48 | } |
35 | 49 |
|
36 | 50 | return null; |
37 | 51 | }; |
38 | 52 |
|
39 | | -module.exports = GetFirstElement; |
| 53 | +module.exports = GetFirst; |
0 commit comments