|
1
|
|
View Code Duplication |
module.exports = function end (arr) { |
|
2
|
|
|
// discuss at: https://locutus.io/php/end/ |
|
3
|
|
|
// original by: Kevin van Zonneveld (https://kvz.io) |
|
4
|
|
|
// bugfixed by: Legaev Andrey |
|
5
|
|
|
// revised by: J A R |
|
6
|
|
|
// revised by: Brett Zamir (https://brett-zamir.me) |
|
7
|
|
|
// improved by: Kevin van Zonneveld (https://kvz.io) |
|
8
|
|
|
// improved by: Kevin van Zonneveld (https://kvz.io) |
|
9
|
|
|
// note 1: Uses global: locutus to store the array pointer |
|
10
|
|
|
// example 1: end({0: 'Kevin', 1: 'van', 2: 'Zonneveld'}) |
|
11
|
|
|
// returns 1: 'Zonneveld' |
|
12
|
|
|
// example 2: end(['Kevin', 'van', 'Zonneveld']) |
|
13
|
|
|
// returns 2: 'Zonneveld' |
|
14
|
|
|
|
|
15
|
|
|
var $global = (typeof window !== 'undefined' ? window : global) |
|
16
|
|
|
$global.$locutus = $global.$locutus || {} |
|
17
|
|
|
var $locutus = $global.$locutus |
|
18
|
|
|
$locutus.php = $locutus.php || {} |
|
19
|
|
|
$locutus.php.pointers = $locutus.php.pointers || [] |
|
20
|
|
|
var pointers = $locutus.php.pointers |
|
21
|
|
|
|
|
22
|
|
|
var indexOf = function (value) { |
|
23
|
|
|
for (var i = 0, length = this.length; i < length; i++) { |
|
24
|
|
|
if (this[i] === value) { |
|
25
|
|
|
return i |
|
26
|
|
|
} |
|
27
|
|
|
} |
|
28
|
|
|
return -1 |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
if (!pointers.indexOf) { |
|
32
|
|
|
pointers.indexOf = indexOf |
|
33
|
|
|
} |
|
34
|
|
|
if (pointers.indexOf(arr) === -1) { |
|
35
|
|
|
pointers.push(arr, 0) |
|
36
|
|
|
} |
|
37
|
|
|
var arrpos = pointers.indexOf(arr) |
|
38
|
|
|
if (Object.prototype.toString.call(arr) !== '[object Array]') { |
|
39
|
|
|
var ct = 0 |
|
40
|
|
|
var val |
|
41
|
|
|
for (var k in arr) { |
|
|
|
|
|
|
42
|
|
|
ct++ |
|
43
|
|
|
val = arr[k] |
|
44
|
|
|
} |
|
45
|
|
|
if (ct === 0) { |
|
46
|
|
|
// Empty |
|
47
|
|
|
return false |
|
48
|
|
|
} |
|
49
|
|
|
pointers[arrpos + 1] = ct - 1 |
|
50
|
|
|
return val |
|
|
|
|
|
|
51
|
|
|
} |
|
52
|
|
|
if (arr.length === 0) { |
|
53
|
|
|
return false |
|
54
|
|
|
} |
|
55
|
|
|
pointers[arrpos + 1] = arr.length - 1 |
|
56
|
|
|
return arr[pointers[arrpos + 1]] |
|
57
|
|
|
} |
|
58
|
|
|
|
When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically: