From 8c46564c0841077b2e844fc7b1f3d00d965b0802 Mon Sep 17 00:00:00 2001 From: Olmo Maldonado Date: Sun, 29 Mar 2009 12:27:00 -0700 Subject: [PATCH] Added Array.item --- Docs/Native/Array.md | 19 +++++++++++++++++++ Source/Native/Array.js | 7 ++++++- Specs/Native/Array.js | 16 ++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/Docs/Native/Array.md b/Docs/Native/Array.md index 7d5e7d89..38142f4a 100644 --- a/Docs/Native/Array.md +++ b/Docs/Native/Array.md @@ -508,6 +508,25 @@ Empties an array. myArray.empty(); //myArray is now [] +Array Method: item {#Array:item} +---------------------------------- + +Returns an item in an array. Function supports negative indxing. + +### Syntax: + + myArray.item(at); + +### Returns: + +* (*mixed*) An item from this array. If this array is empty, returns null. + +### Examples: + + var myArray = ['old', 'data']; + myArray.item(0); //'old' + myArray.item(-1); //'data' + Array Method: flatten {#Array:flatten} -------------------------------------- diff --git a/Source/Native/Array.js b/Source/Native/Array.js index 9d102297..53057942 100644 --- a/Source/Native/Array.js +++ b/Source/Native/Array.js @@ -76,9 +76,14 @@ Array.implement({ for (var i = 0, j = array.length; i < j; i++) this.push(array[i]); return this; }, + + item: function(at){ + if (at < 0) at += this.length; + return this[at]; + }, getLast: function(){ - return (this.length) ? this[this.length - 1] : null; + return this.item(-1); }, getRandom: function(){ diff --git a/Specs/Native/Array.js b/Specs/Native/Array.js index 96ae64cc..c6f1d972 100644 --- a/Specs/Native/Array.js +++ b/Specs/Native/Array.js @@ -160,6 +160,22 @@ describe("Array Methods", { 'should empty the array': function(){ var arr = [1,2,3,4].empty(); value_of(arr).should_be([]); + }, + + // Array.item + + 'should return the item': function(){ + var arr = [1,2,3,4]; + value_of(arr.item(0)).should_be(1); + value_of(array.item(-1)).should_be(4); + }, + + 'should retun null if no item or no items in the array': function(){ + var arr = [1,2,3,4]; + value_of(arr.item(10)).should_be(null); + + arr = []; + value_of(arr.item(-1)).should_be(null); } }); -- 2.11.4.GIT