SlideShare a Scribd company logo
Prototype  Array
Introduction Prototype extends all native Javascript arrays with quite a few powerful methods.This is done in two ways: It mixes in the Enumerable module, which brings a ton of methods in already. It adds quite a few extra methods, which are documented in this section.  With Prototype, arrays become much, much more than the trivial objects we were used to manipulate, limiting ourselves to using their length property and their [] indexing operator. They become very powerful objects, that greatly simplify the code for 99% of the common use cases involving them.
Important Issues Many JavaScript authors have been misled into using the for…in JavaScript construct to loop over array elements. This kind of code just won’t work with Prototype. You see, the ECMA 262 standard, which defines ECMAScript 3rd edition, supposedly implemented by all major browsers including  MSIE , defines numerous methods on Array (§15.4.4), including such nice methods as concat, join, pop and push, to name but a few among the ten methods specified.
This same standard explicitely defines that the for…in construct (§12.6.4) exists to  enumerate the properties  of the object appearing on the right side of the in keyword. Only properties specifically marked as non-enumerable are ignored by such a loop. By default, the prototype and the length properties are so marked, which prevents you from enumerating over array methods when using for…in. This comfort led developers to use for…in as a shortcut for indexing loops, when it is not its actual purpose. However, Prototype has no way to mark the methods it adds to Array.prototype as non-enumerable. Therefore, using for…in on arrays when using Prototype will enumerate all extended methods as well, such as those coming from the Enumerable module, and those Prototype puts in the Array namespace (described in this section, and listed further below).
Example; You can revert to vanilla loops:     for  ( var   index  =  0 ;  index  < myArray.length; ++ index ) {      var  item = myArray[ index ];      // Your code working on item here...    }     Or you can use iterators, such as each :      myArray.each( function (item) {      // Your code working on item here...   });    This side-effect enforcement of the true purpose of for…in is actually not so much of a burden: as you’ll see, most of what you used to loop over arrays for can be concisely done using the new methods provided by Array or the mixed-in Enumerable module. So manual loops should be fairly rare.
By using iterators with lexical closures (anonymous functions that you pass to the iterators, that get invoked at every loop iteration), such as each, or relying on repetitive array construction (such as uniq), may yield unsatisfactory performance. In such cases, you’re better off writing manual indexing loops, but take care then to cache the length property and use the prefix ++ operator:     // Custom loop with cached length property: maximum full-loop performance on very large arrays!    for  ( var   index  =  0 , len = myArray.length;  index  < len; ++ index ) {      var  item = myArray[ index ];      // Your code working on item here...     }   
Moduleindex clear :: Array   clear() -> Array  -Clears the array (makes it empty). Example:   var  guys = [ 'Sam' ,  'Justin' ,  'Andrew' ,  'Dan' ];  guys.clear(); // -> [] guys // -> []   clone :: Array   clone() -> newArray  -Returns a duplicate of the array, leaving the original array intact. Example: var  fruits = [ 'Apples' ,  'Oranges' ];  var  myFavs = fruits.clone(); myFavs.pop();  // fruits -> ['Apples', 'Oranges'] // myFavs -> ['Apples']
compact :: Array   compact() -> newArray  -Returns a new version of the array, without any null/undefined values. Example: [ 'frank' , ,  'sue' , ,  'sally' ,  null ].compact()   // -> ['frank', 'sue', 'sally'] each :: Array   each(iterator) -> Array  -Iterates over the array in ascending numerical index order. This is actually the each method from the mixed-in Enumerable module.  It is documented here to clearly state the order of iteration. Example: [ 'one' ,  'two' ,  'three' ].each( function (s) {    alert(s); }); [  'hello' ,  'world' ].each( function (s,  index ) {    alert( index  +  ': '  + s); }); // alerts -> '0: hello' then '1: world'
first :: Array   first() -> value  -Returns the first item in the array, or undefined if the array is empty. Example: [ 'Ruby' ,  'Php' ,  'Python' ].first() // -> 'Ruby'   [].first() // -> undefined   flatten :: Array   flatten() -> newArray  -Returns a “flat” (one-dimensional) version of the array. Nested arrays are recursively injected “inline.” This can prove very useful when handling the results of a recursive collection algorithm, for instance. Example: [ 'frank' , [ 'bob' ,  'lisa' ], [ 'jill' , [ 'tom' ,  'sally' ]]].flatten()   // -> ['frank', 'bob', 'lisa', 'jill', 'tom', 'sally']  
from :: Array   Array.from(iterable) -> actualArray  -Clones an existing array or creates a new one from an array-like collection. This is an alias for the $A() method.  $A() method $A(iterable) -> actualArray  -Accepts an array-like collection (anything with numeric indices) and returns its equivalent as an actual Array object. This method is a convenience alias of Array.from, but is the preferred way of casting to an Array.  Example: var  paras =  $A (document.getElementsByTagName( 'p' )); paras.each(Element.hide); $(paras.last()).show();
indexOf :: Array   indexOf(value) -> position  -Returns the position of the first occurrence of the argument within the array. If the argument doesn’t exist in the array, returns -1. Note: this uses the == equivalence operator, not the === strict equality operator. The bottom example below illustrates this. Minor note: this uses a plain old optimized indexing loop, so there’s no risk of extensions being detected by this method Example: [ 3 ,  5 ,  6 ,  1 ,  20 ].indexOf( 1 ) // -> 3  [ 3 ,  5 ,  6 ,  1 ,  20 ].indexOf( 90 ) // -> -1  [ 0 ,  false ,  15 ].indexOf( false ) // -> 0 instead of 1, because 0 == false!
inspect :: Array   inspect() -> String  -Returns the debug-oriented string representation of an array. Example:   [ 'Apples' , {good:  'yes' , bad:  'no' },  3 ,  34 ].inspect()  // -> &quot;['Apples', [object Object], 3, 34]“ NOTE: If you want to simply join the string elements of an array, use the native join method instead:  [ 'apples' ,  'bananas' ,  'kiwis' ].join( ', ' )  // -> 'apples, bananas, kiwis‘ see also inspect in object.inspect() Object.inspect(obj) -> String  -Returns the debug-oriented string representation of the object Example: Object.inspect() // -> 'undefined'  Object.inspect( null ) // -> 'null'  Object.inspect( false ) // -> 'false'  Object.inspect([ 1 ,  2 ,  3 ]) // -> '[1, 2, 3]'  Object.inspect( 'hello' ) // -> &quot;'hello'&quot;
last :: Array   last() -> value  -Returns the last item in the array, or undefined if the array is empty. Example: [ 'Ruby' ,  'Php' ,  'Python' ].last() // -> 'Python'   [].last() // -> undefined reduce :: Array   reduce() -> Array | singleValue  -Reduces arrays: one-element arrays are turned into their unique element, while multiple element arrays are returned untouched. Example: [ 3 ].reduce(); // -> 3   [ 3 ,  5 ].reduce(); // -> [3, 5]  
  reverse :: Array   reverse([inline = true]) -> Array  -Returns the reversed version of the array. By default, directly reverses the original. If inline is set to false, uses a clone of the original array. Example: var  nums = [ 3 ,  5 ,  6 ,  1 ,  20 ];  nums.reverse( false ) // -> [20, 1, 6, 5, 3] nums // -> [3, 5, 6, 1, 20]  nums.reverse() // -> [20, 1, 6, 5, 3] nums // -> [20, 1, 6, 5, 3] size   :: Array size() -> Number  -Returns the size of the array. This is just a local optimization of the mixed-in size method from the Enumerable module, which avoids array cloning and uses the array’s native length property. Example: $R ( 1 ,  10 ).size() // -> 10  [ 'hello' ,  42 ,  true ].size() // -> 3  $H ().size() // -> 0
toArray :: Array   toArray() -> newArray  -This is just a local optimization of the mixed-in toArray from Enumerable. This version aliases to clone, avoiding the default iterative behavior    See array.clone toJSON (1.5.1) :: Array   toJSON() -> String  -Returns a JSON string. Example: [ 'a' , {b:  null }].toJSON(); //-> '[&quot;a&quot;,{&quot;b&quot;:null}]'
Uniq :: Array   uniq() -> newArray   -Produces a duplicate-free version of an array. If no duplicates are found, the original array is returned. Example: [ 'Sam' ,  'Justin' ,  'Andrew' ,  'Dan' ,  'Sam' ].uniq(); // -> ['Sam', 'Justin', 'Andrew', 'Dan']   [ 'Prototype' ,  'prototype' ].uniq(); // -> ['Prototype', 'prototype'] because String comparison is case-sensitive   Performance considerations   On large arrays with duplicates, this method has a potentially large performance cost:   Since it does not require the array to be sorted, it has quadratic complexity. Since it relies on JavaScript’s Array.concat, it will yield a new, intermediary array every time it encounters a new value (a value that wasn’t already in the result array).  More efficient implementations could be devised.  This page will get updated if such an optimization is committed.
Without :: Array   without(value...) -> newArray  -Produces a new version of the array that does not contain any of the specified values. Example: [ 3 ,  5 ,  6 ,  1 ,  20 ].without( 3 ) // -> [5, 6, 1, 20]   [ 3 ,  5 ,  6 ,  1 ,  20 ].without( 20 ,  6 ) // -> [3, 5, 1]
Ad

More Related Content

What's hot (20)

Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
Zaar Hai
 
Advanced python
Advanced pythonAdvanced python
Advanced python
EU Edge
 
Template Haskell
Template HaskellTemplate Haskell
Template Haskell
Sergey Stretovich
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
Array String - Web Programming
Array String - Web ProgrammingArray String - Web Programming
Array String - Web Programming
Amirul Azhar
 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick off
Andrea Gangemi
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
gosain20
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
None
 
Docopt
DocoptDocopt
Docopt
René Ribaud
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Dave Cross
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
Dave Cross
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
Kaz Yoshikawa
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
Dave Cross
 
Mastering Grammars with PetitParser
Mastering Grammars with PetitParserMastering Grammars with PetitParser
Mastering Grammars with PetitParser
Lukas Renggli
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
Dave Cross
 
Composing method
Composing methodComposing method
Composing method
С. Ариука
 
Erubis徹底解説
Erubis徹底解説Erubis徹底解説
Erubis徹底解説
kwatch
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List Comprehensions
P3 InfoTech Solutions Pvt. Ltd.
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
Zaar Hai
 
Advanced python
Advanced pythonAdvanced python
Advanced python
EU Edge
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
Array String - Web Programming
Array String - Web ProgrammingArray String - Web Programming
Array String - Web Programming
Amirul Azhar
 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick off
Andrea Gangemi
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
gosain20
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
None
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Dave Cross
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
Dave Cross
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
Kaz Yoshikawa
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
Dave Cross
 
Mastering Grammars with PetitParser
Mastering Grammars with PetitParserMastering Grammars with PetitParser
Mastering Grammars with PetitParser
Lukas Renggli
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
Dave Cross
 
Erubis徹底解説
Erubis徹底解説Erubis徹底解説
Erubis徹底解説
kwatch
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List Comprehensions
P3 InfoTech Solutions Pvt. Ltd.
 

Viewers also liked (8)

A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
 
Extending built in objects
Extending built in objectsExtending built in objects
Extending built in objects
Muhammad Ahmed
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpreted
Martha Schumann
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
Thomas Hunter II
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
Simon Su
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
ecker
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
raja kvk
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
Designveloper
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
 
Extending built in objects
Extending built in objectsExtending built in objects
Extending built in objects
Muhammad Ahmed
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpreted
Martha Schumann
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
Simon Su
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
ecker
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
raja kvk
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
Designveloper
 
Ad

Similar to Array (20)

JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
Arrays the beginners and intermediate.pptx
Arrays the beginners and intermediate.pptxArrays the beginners and intermediate.pptx
Arrays the beginners and intermediate.pptx
ZSNQuest
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
Sopan Shewale
 
Enumerable
EnumerableEnumerable
Enumerable
mussawir20
 
How Xslate Works
How Xslate WorksHow Xslate Works
How Xslate Works
Goro Fuji
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
Shahzad
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
UmairMughal74
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
iammukesh1075
 
operator overloading concept in oops lecture12.ppt
operator overloading concept in oops lecture12.pptoperator overloading concept in oops lecture12.ppt
operator overloading concept in oops lecture12.ppt
SriGovndarajaSwamyAr
 
OOP OOOOOverloading Concept lecture12.ppt
OOP OOOOOverloading  Concept lecture12.pptOOP OOOOOverloading  Concept lecture12.ppt
OOP OOOOOverloading Concept lecture12.ppt
SriGovndarajaSwamyAr
 
JavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHatJavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimization
PrestaShop
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
OXUS 20
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
application developer
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
Frayosh Wadia
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
Arrays the beginners and intermediate.pptx
Arrays the beginners and intermediate.pptxArrays the beginners and intermediate.pptx
Arrays the beginners and intermediate.pptx
ZSNQuest
 
How Xslate Works
How Xslate WorksHow Xslate Works
How Xslate Works
Goro Fuji
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
Shahzad
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
iammukesh1075
 
operator overloading concept in oops lecture12.ppt
operator overloading concept in oops lecture12.pptoperator overloading concept in oops lecture12.ppt
operator overloading concept in oops lecture12.ppt
SriGovndarajaSwamyAr
 
OOP OOOOOverloading Concept lecture12.ppt
OOP OOOOOverloading  Concept lecture12.pptOOP OOOOOverloading  Concept lecture12.ppt
OOP OOOOOverloading Concept lecture12.ppt
SriGovndarajaSwamyAr
 
JavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHatJavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimization
PrestaShop
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
OXUS 20
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
Ad

More from mussawir20 (20)

Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllers
mussawir20
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
mussawir20
 
Database Design Process
Database Design ProcessDatabase Design Process
Database Design Process
mussawir20
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xml
mussawir20
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
Php Sq Lite
Php Sq LitePhp Sq Lite
Php Sq Lite
mussawir20
 
Php Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
mussawir20
 
Php Rss
Php RssPhp Rss
Php Rss
mussawir20
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 
Php Oop
Php OopPhp Oop
Php Oop
mussawir20
 
Php My Sql
Php My SqlPhp My Sql
Php My Sql
mussawir20
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
mussawir20
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
mussawir20
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
mussawir20
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Javascript Oop
Javascript OopJavascript Oop
Javascript Oop
mussawir20
 
Html
HtmlHtml
Html
mussawir20
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Object Range
Object RangeObject Range
Object Range
mussawir20
 
Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllers
mussawir20
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
mussawir20
 
Database Design Process
Database Design ProcessDatabase Design Process
Database Design Process
mussawir20
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xml
mussawir20
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
Php Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
mussawir20
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
mussawir20
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
mussawir20
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
mussawir20
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Javascript Oop
Javascript OopJavascript Oop
Javascript Oop
mussawir20
 

Recently uploaded (20)

ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Social Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTechSocial Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTech
Steve Jonas
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Are Cloud PBX Providers in India Reliable for Small Businesses (1).pdf
Are Cloud PBX Providers in India Reliable for Small Businesses (1).pdfAre Cloud PBX Providers in India Reliable for Small Businesses (1).pdf
Are Cloud PBX Providers in India Reliable for Small Businesses (1).pdf
Telecoms Supermarket
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Unlocking the Power of IVR: A Comprehensive Guide
Unlocking the Power of IVR: A Comprehensive GuideUnlocking the Power of IVR: A Comprehensive Guide
Unlocking the Power of IVR: A Comprehensive Guide
vikasascentbpo
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Vaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without HallucinationsVaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without Hallucinations
john409870
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Social Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTechSocial Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTech
Steve Jonas
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Are Cloud PBX Providers in India Reliable for Small Businesses (1).pdf
Are Cloud PBX Providers in India Reliable for Small Businesses (1).pdfAre Cloud PBX Providers in India Reliable for Small Businesses (1).pdf
Are Cloud PBX Providers in India Reliable for Small Businesses (1).pdf
Telecoms Supermarket
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Unlocking the Power of IVR: A Comprehensive Guide
Unlocking the Power of IVR: A Comprehensive GuideUnlocking the Power of IVR: A Comprehensive Guide
Unlocking the Power of IVR: A Comprehensive Guide
vikasascentbpo
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Vaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without HallucinationsVaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without Hallucinations
john409870
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 

Array

  • 2. Introduction Prototype extends all native Javascript arrays with quite a few powerful methods.This is done in two ways: It mixes in the Enumerable module, which brings a ton of methods in already. It adds quite a few extra methods, which are documented in this section.  With Prototype, arrays become much, much more than the trivial objects we were used to manipulate, limiting ourselves to using their length property and their [] indexing operator. They become very powerful objects, that greatly simplify the code for 99% of the common use cases involving them.
  • 3. Important Issues Many JavaScript authors have been misled into using the for…in JavaScript construct to loop over array elements. This kind of code just won’t work with Prototype. You see, the ECMA 262 standard, which defines ECMAScript 3rd edition, supposedly implemented by all major browsers including MSIE , defines numerous methods on Array (§15.4.4), including such nice methods as concat, join, pop and push, to name but a few among the ten methods specified.
  • 4. This same standard explicitely defines that the for…in construct (§12.6.4) exists to enumerate the properties of the object appearing on the right side of the in keyword. Only properties specifically marked as non-enumerable are ignored by such a loop. By default, the prototype and the length properties are so marked, which prevents you from enumerating over array methods when using for…in. This comfort led developers to use for…in as a shortcut for indexing loops, when it is not its actual purpose. However, Prototype has no way to mark the methods it adds to Array.prototype as non-enumerable. Therefore, using for…in on arrays when using Prototype will enumerate all extended methods as well, such as those coming from the Enumerable module, and those Prototype puts in the Array namespace (described in this section, and listed further below).
  • 5. Example; You can revert to vanilla loops:     for  ( var   index  =  0 ;  index  < myArray.length; ++ index ) {      var  item = myArray[ index ];      // Your code working on item here...    }     Or you can use iterators, such as each :      myArray.each( function (item) {      // Your code working on item here...   });    This side-effect enforcement of the true purpose of for…in is actually not so much of a burden: as you’ll see, most of what you used to loop over arrays for can be concisely done using the new methods provided by Array or the mixed-in Enumerable module. So manual loops should be fairly rare.
  • 6. By using iterators with lexical closures (anonymous functions that you pass to the iterators, that get invoked at every loop iteration), such as each, or relying on repetitive array construction (such as uniq), may yield unsatisfactory performance. In such cases, you’re better off writing manual indexing loops, but take care then to cache the length property and use the prefix ++ operator:     // Custom loop with cached length property: maximum full-loop performance on very large arrays!    for  ( var   index  =  0 , len = myArray.length;  index  < len; ++ index ) {      var  item = myArray[ index ];      // Your code working on item here...     }   
  • 7. Moduleindex clear :: Array   clear() -> Array  -Clears the array (makes it empty). Example:   var  guys = [ 'Sam' ,  'Justin' ,  'Andrew' ,  'Dan' ];  guys.clear(); // -> [] guys // -> []   clone :: Array   clone() -> newArray  -Returns a duplicate of the array, leaving the original array intact. Example: var  fruits = [ 'Apples' ,  'Oranges' ];  var  myFavs = fruits.clone(); myFavs.pop();  // fruits -> ['Apples', 'Oranges'] // myFavs -> ['Apples']
  • 8. compact :: Array   compact() -> newArray  -Returns a new version of the array, without any null/undefined values. Example: [ 'frank' , ,  'sue' , ,  'sally' ,  null ].compact()   // -> ['frank', 'sue', 'sally'] each :: Array   each(iterator) -> Array  -Iterates over the array in ascending numerical index order. This is actually the each method from the mixed-in Enumerable module. It is documented here to clearly state the order of iteration. Example: [ 'one' ,  'two' ,  'three' ].each( function (s) {    alert(s); }); [  'hello' ,  'world' ].each( function (s,  index ) {    alert( index  +  ': '  + s); }); // alerts -> '0: hello' then '1: world'
  • 9. first :: Array   first() -> value  -Returns the first item in the array, or undefined if the array is empty. Example: [ 'Ruby' ,  'Php' ,  'Python' ].first() // -> 'Ruby'   [].first() // -> undefined   flatten :: Array   flatten() -> newArray  -Returns a “flat” (one-dimensional) version of the array. Nested arrays are recursively injected “inline.” This can prove very useful when handling the results of a recursive collection algorithm, for instance. Example: [ 'frank' , [ 'bob' ,  'lisa' ], [ 'jill' , [ 'tom' ,  'sally' ]]].flatten()   // -> ['frank', 'bob', 'lisa', 'jill', 'tom', 'sally']  
  • 10. from :: Array   Array.from(iterable) -> actualArray  -Clones an existing array or creates a new one from an array-like collection. This is an alias for the $A() method. $A() method $A(iterable) -> actualArray  -Accepts an array-like collection (anything with numeric indices) and returns its equivalent as an actual Array object. This method is a convenience alias of Array.from, but is the preferred way of casting to an Array.  Example: var  paras =  $A (document.getElementsByTagName( 'p' )); paras.each(Element.hide); $(paras.last()).show();
  • 11. indexOf :: Array   indexOf(value) -> position  -Returns the position of the first occurrence of the argument within the array. If the argument doesn’t exist in the array, returns -1. Note: this uses the == equivalence operator, not the === strict equality operator. The bottom example below illustrates this. Minor note: this uses a plain old optimized indexing loop, so there’s no risk of extensions being detected by this method Example: [ 3 ,  5 ,  6 ,  1 ,  20 ].indexOf( 1 ) // -> 3  [ 3 ,  5 ,  6 ,  1 ,  20 ].indexOf( 90 ) // -> -1  [ 0 ,  false ,  15 ].indexOf( false ) // -> 0 instead of 1, because 0 == false!
  • 12. inspect :: Array   inspect() -> String  -Returns the debug-oriented string representation of an array. Example:   [ 'Apples' , {good:  'yes' , bad:  'no' },  3 ,  34 ].inspect()  // -> &quot;['Apples', [object Object], 3, 34]“ NOTE: If you want to simply join the string elements of an array, use the native join method instead:  [ 'apples' ,  'bananas' ,  'kiwis' ].join( ', ' )  // -> 'apples, bananas, kiwis‘ see also inspect in object.inspect() Object.inspect(obj) -> String  -Returns the debug-oriented string representation of the object Example: Object.inspect() // -> 'undefined'  Object.inspect( null ) // -> 'null'  Object.inspect( false ) // -> 'false'  Object.inspect([ 1 ,  2 ,  3 ]) // -> '[1, 2, 3]'  Object.inspect( 'hello' ) // -> &quot;'hello'&quot;
  • 13. last :: Array   last() -> value  -Returns the last item in the array, or undefined if the array is empty. Example: [ 'Ruby' ,  'Php' ,  'Python' ].last() // -> 'Python'   [].last() // -> undefined reduce :: Array   reduce() -> Array | singleValue  -Reduces arrays: one-element arrays are turned into their unique element, while multiple element arrays are returned untouched. Example: [ 3 ].reduce(); // -> 3   [ 3 ,  5 ].reduce(); // -> [3, 5]  
  • 14.   reverse :: Array   reverse([inline = true]) -> Array  -Returns the reversed version of the array. By default, directly reverses the original. If inline is set to false, uses a clone of the original array. Example: var  nums = [ 3 ,  5 ,  6 ,  1 ,  20 ];  nums.reverse( false ) // -> [20, 1, 6, 5, 3] nums // -> [3, 5, 6, 1, 20]  nums.reverse() // -> [20, 1, 6, 5, 3] nums // -> [20, 1, 6, 5, 3] size  :: Array size() -> Number  -Returns the size of the array. This is just a local optimization of the mixed-in size method from the Enumerable module, which avoids array cloning and uses the array’s native length property. Example: $R ( 1 ,  10 ).size() // -> 10  [ 'hello' ,  42 ,  true ].size() // -> 3  $H ().size() // -> 0
  • 15. toArray :: Array   toArray() -> newArray  -This is just a local optimization of the mixed-in toArray from Enumerable. This version aliases to clone, avoiding the default iterative behavior   See array.clone toJSON (1.5.1) :: Array   toJSON() -> String  -Returns a JSON string. Example: [ 'a' , {b:  null }].toJSON(); //-> '[&quot;a&quot;,{&quot;b&quot;:null}]'
  • 16. Uniq :: Array   uniq() -> newArray   -Produces a duplicate-free version of an array. If no duplicates are found, the original array is returned. Example: [ 'Sam' ,  'Justin' ,  'Andrew' ,  'Dan' ,  'Sam' ].uniq(); // -> ['Sam', 'Justin', 'Andrew', 'Dan']   [ 'Prototype' ,  'prototype' ].uniq(); // -> ['Prototype', 'prototype'] because String comparison is case-sensitive   Performance considerations   On large arrays with duplicates, this method has a potentially large performance cost:   Since it does not require the array to be sorted, it has quadratic complexity. Since it relies on JavaScript’s Array.concat, it will yield a new, intermediary array every time it encounters a new value (a value that wasn’t already in the result array).  More efficient implementations could be devised. This page will get updated if such an optimization is committed.
  • 17. Without :: Array   without(value...) -> newArray  -Produces a new version of the array that does not contain any of the specified values. Example: [ 3 ,  5 ,  6 ,  1 ,  20 ].without( 3 ) // -> [5, 6, 1, 20]   [ 3 ,  5 ,  6 ,  1 ,  20 ].without( 20 ,  6 ) // -> [3, 5, 1]