IE
Any version of IE
lt IE version
Versions less than version
lte IE version
Versions less than or equal to version
IE version
Only version version
gte IE version
Versions greater than or equal to version
gt IE version
Versions greater than version
IE 6 and below
* html {}
IE 7 and below
*:first-child+html {} * html {}
IE 7 only
*:first-child+html {}
IE 7 and modern browsers only
html>body {}
Modern browsers only (not IE 7)
html>/**/body {}
Recent Opera versions 9 and below
html:first-child {}
Tuesday, September 20, 2011
Basic Ajax Program
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
WEB PERFORMANCE RULES - YSLOW
Yahoo!'s Exceptional Performance team has identified 34 rules that affect web page performance. YSlow's web page analysis is based on the 23 of these 34 rules that are testable. These testable rules are listed below roughly in order of importance and effectiveness. Studies have shown that web page response time can be improved by 25% to 50% by following these rules.
Minimize HTTP Requests
Use a Content Delivery Network
Avoid empty src or href
Add an Expires or a Cache-Control Header
Gzip Components
Put StyleSheets at the Top
Put Scripts at the Bottom
Avoid CSS Expressions
Make JavaScript and CSS External
Reduce DNS Lookups
Minify JavaScript and CSS
Avoid Redirects
Remove Duplicate Scripts
Configure ETags
Make AJAX Cacheable
Use GET for AJAX Requests
Reduce the Number of DOM Elements
No 404s
Reduce Cookie Size
Use Cookie-Free Domains for Components
Avoid Filters
Do Not Scale Images in HTML
Make favicon.ico Small and Cacheable
Minimize HTTP Requests
Use a Content Delivery Network
Avoid empty src or href
Add an Expires or a Cache-Control Header
Gzip Components
Put StyleSheets at the Top
Put Scripts at the Bottom
Avoid CSS Expressions
Make JavaScript and CSS External
Reduce DNS Lookups
Minify JavaScript and CSS
Avoid Redirects
Remove Duplicate Scripts
Configure ETags
Make AJAX Cacheable
Use GET for AJAX Requests
Reduce the Number of DOM Elements
No 404s
Reduce Cookie Size
Use Cookie-Free Domains for Components
Avoid Filters
Do Not Scale Images in HTML
Make favicon.ico Small and Cacheable
Web Testing: Complete guide on testing web applications
Let’s have first web testing checklist.
1) Functionality Testing
2) Usability testing
3) Interface testing
4) Compatibility testing
5) Performance testing
6) Security testing
1) Functionality Testing:
Test for – all the links in web pages, database connection, forms used in the web pages for submitting or getting information from user, Cookie testing.
Check all the links:
Test the outgoing links from all the pages from specific domain under test.
Test all internal links.
Test links jumping on the same pages.
Test links used to send the email to admin or other users from web pages.
Test to check if there are any orphan pages.
Lastly in link checking, check for broken links in all above-mentioned links.
Test forms in all pages:
Forms are the integral part of any web site. Forms are used to get information from users and to keep interaction with them. So what should be checked on these forms?
First check all the validations on each field.
Check for the default values of fields.
Wrong inputs to the fields in the forms.
Options to create forms if any, form delete, view or modify the forms.
Let’s take example of the search engine project currently I am working on, In this project we have advertiser and affiliate signup steps. Each sign up step is different but dependent on other steps. So sign up flow should get executed correctly. There are different field validations like email Ids, User financial info validations. All these validations should get checked in manual or automated web testing.
Cookies testing:
Cookies are small files stored on user machine. These are basically used to maintain the session mainly login sessions. Test the application by enabling or disabling the cookies in your browser options. Test if the cookies are encrypted before writing to user machine. If you are testing the session cookies (i.e. cookies expire after the sessions ends) check for login sessions and user stats after session end. Check effect on application security by deleting the cookies. (I will soon write separate article on cookie testing)
Validate your HTML/CSS:
If you are optimizing your site for Search engines then HTML/CSS validation is very important. Mainly validate the site for HTML syntax errors. Check if site is crawlable to different search engines.
Database testing:
Data consistency is very important in web application. Check for data integrity and errors while you edit, delete, modify the forms or do any DB related functionality.
Check if all the database queries are executing correctly, data is retrieved correctly and also updated correctly. More on database testing could be load on DB, we will address this in web load or performance testing below.
2) Usability Testing:
Test for navigation:
Navigation means how the user surfs the web pages, different controls like buttons, boxes or how user using the links on the pages to surf different pages.
Usability testing includes:
Web site should be easy to use. Instructions should be provided clearly. Check if the provided instructions are correct means whether they satisfy purpose.
Main menu should be provided on each page. It should be consistent.
Content checking:
Content should be logical and easy to understand. Check for spelling errors. Use of dark colors annoys users and should not be used in site theme. You can follow some standards that are used for web page and content building. These are common accepted standards like as I mentioned above about annoying colors, fonts, frames etc.
Content should be meaningful. All the anchor text links should be working properly. Images should be placed properly with proper sizes.
These are some basic standards that should be followed in web development. Your task is to validate all for UI testing
Other user information for user help:
Like search option, sitemap, help files etc. Sitemap should be present with all the links in web sites with proper tree view of navigation. Check for all links on the sitemap.
“Search in the site” option will help users to find content pages they are looking for easily and quickly. These are all optional items and if present should be validated.
3) Interface Testing:
The main interfaces are:
Web server and application server interface
Application server and Database server interface.
Check if all the interactions between these servers are executed properly. Errors are handled properly. If database or web server returns any error message for any query by application server then application server should catch and display these error messages appropriately to users. Check what happens if user interrupts any transaction in-between? Check what happens if connection to web server is reset in between?
4) Compatibility Testing:
Compatibility of your web site is very important testing aspect. See which compatibility test to be executed:
Browser compatibility
Operating system compatibility
Mobile browsing
Printing options
Browser compatibility:
In my web-testing career I have experienced this as most influencing part on web site testing.
Some applications are very dependent on browsers. Different browsers have different configurations and settings that your web page should be compatible with. Your web site coding should be cross browser platform compatible. If you are using java scripts or AJAX calls for UI functionality, performing security checks or validations then give more stress on browser compatibility testing of your web application.
Test web application on different browsers like Internet explorer, Firefox, Netscape navigator, AOL, Safari, Opera browsers with different versions.
OS compatibility:
Some functionality in your web application is may not be compatible with all operating systems. All new technologies used in web development like graphics designs, interface calls like different API’s may not be available in all Operating Systems.
Test your web application on different operating systems like Windows, Unix, MAC, Linux, Solaris with different OS flavors.
Mobile browsing:
This is new technology age. So in future Mobile browsing will rock. Test your web pages on mobile browsers. Compatibility issues may be there on mobile.
Printing options:
If you are giving page-printing options then make sure fonts, page alignment, page graphics getting printed properly. Pages should be fit to paper size or as per the size mentioned in printing option.
5) Performance testing:
Web application should sustain to heavy load. Web performance testing should include:
Web Load Testing
Web Stress Testing
Test application performance on different internet connection speed.
In web load testing test if many users are accessing or requesting the same page. Can system sustain in peak load times? Site should handle many simultaneous user requests, large input data from users, Simultaneous connection to DB, heavy load on specific pages etc.
Stress testing: Generally stress means stretching the system beyond its specification limits. Web stress testing is performed to break the site by giving stress and checked how system reacts to stress and how system recovers from crashes.
Stress is generally given on input fields, login and sign up areas.
In web performance testing web site functionality on different operating systems, different hardware platforms is checked for software, hardware memory leakage errors,
6) Security Testing:
Following are some test cases for web security testing:
Test by pasting internal url directly into browser address bar without login. Internal pages should not open.
If you are logged in using username and password and browsing internal pages then try changing url options directly. I.e. If you are checking some publisher site statistics with publisher site ID= 123. Try directly changing the url site ID parameter to different site ID which is not related to logged in user. Access should denied for this user to view others stats.
Try some invalid inputs in input fields like login username, password, input text boxes. Check the system reaction on all invalid inputs.
Web directories or files should not be accessible directly unless given download option.
Test the CAPTCHA for automates scripts logins.
Test if SSL is used for security measures. If used proper message should get displayed when user switch from non-secure http:// pages to secure https:// pages and vice versa.
All transactions, error messages, security breach attempts should get logged in log files somewhere on web server.
1) Functionality Testing
2) Usability testing
3) Interface testing
4) Compatibility testing
5) Performance testing
6) Security testing
1) Functionality Testing:
Test for – all the links in web pages, database connection, forms used in the web pages for submitting or getting information from user, Cookie testing.
Check all the links:
Test the outgoing links from all the pages from specific domain under test.
Test all internal links.
Test links jumping on the same pages.
Test links used to send the email to admin or other users from web pages.
Test to check if there are any orphan pages.
Lastly in link checking, check for broken links in all above-mentioned links.
Test forms in all pages:
Forms are the integral part of any web site. Forms are used to get information from users and to keep interaction with them. So what should be checked on these forms?
First check all the validations on each field.
Check for the default values of fields.
Wrong inputs to the fields in the forms.
Options to create forms if any, form delete, view or modify the forms.
Let’s take example of the search engine project currently I am working on, In this project we have advertiser and affiliate signup steps. Each sign up step is different but dependent on other steps. So sign up flow should get executed correctly. There are different field validations like email Ids, User financial info validations. All these validations should get checked in manual or automated web testing.
Cookies testing:
Cookies are small files stored on user machine. These are basically used to maintain the session mainly login sessions. Test the application by enabling or disabling the cookies in your browser options. Test if the cookies are encrypted before writing to user machine. If you are testing the session cookies (i.e. cookies expire after the sessions ends) check for login sessions and user stats after session end. Check effect on application security by deleting the cookies. (I will soon write separate article on cookie testing)
Validate your HTML/CSS:
If you are optimizing your site for Search engines then HTML/CSS validation is very important. Mainly validate the site for HTML syntax errors. Check if site is crawlable to different search engines.
Database testing:
Data consistency is very important in web application. Check for data integrity and errors while you edit, delete, modify the forms or do any DB related functionality.
Check if all the database queries are executing correctly, data is retrieved correctly and also updated correctly. More on database testing could be load on DB, we will address this in web load or performance testing below.
2) Usability Testing:
Test for navigation:
Navigation means how the user surfs the web pages, different controls like buttons, boxes or how user using the links on the pages to surf different pages.
Usability testing includes:
Web site should be easy to use. Instructions should be provided clearly. Check if the provided instructions are correct means whether they satisfy purpose.
Main menu should be provided on each page. It should be consistent.
Content checking:
Content should be logical and easy to understand. Check for spelling errors. Use of dark colors annoys users and should not be used in site theme. You can follow some standards that are used for web page and content building. These are common accepted standards like as I mentioned above about annoying colors, fonts, frames etc.
Content should be meaningful. All the anchor text links should be working properly. Images should be placed properly with proper sizes.
These are some basic standards that should be followed in web development. Your task is to validate all for UI testing
Other user information for user help:
Like search option, sitemap, help files etc. Sitemap should be present with all the links in web sites with proper tree view of navigation. Check for all links on the sitemap.
“Search in the site” option will help users to find content pages they are looking for easily and quickly. These are all optional items and if present should be validated.
3) Interface Testing:
The main interfaces are:
Web server and application server interface
Application server and Database server interface.
Check if all the interactions between these servers are executed properly. Errors are handled properly. If database or web server returns any error message for any query by application server then application server should catch and display these error messages appropriately to users. Check what happens if user interrupts any transaction in-between? Check what happens if connection to web server is reset in between?
4) Compatibility Testing:
Compatibility of your web site is very important testing aspect. See which compatibility test to be executed:
Browser compatibility
Operating system compatibility
Mobile browsing
Printing options
Browser compatibility:
In my web-testing career I have experienced this as most influencing part on web site testing.
Some applications are very dependent on browsers. Different browsers have different configurations and settings that your web page should be compatible with. Your web site coding should be cross browser platform compatible. If you are using java scripts or AJAX calls for UI functionality, performing security checks or validations then give more stress on browser compatibility testing of your web application.
Test web application on different browsers like Internet explorer, Firefox, Netscape navigator, AOL, Safari, Opera browsers with different versions.
OS compatibility:
Some functionality in your web application is may not be compatible with all operating systems. All new technologies used in web development like graphics designs, interface calls like different API’s may not be available in all Operating Systems.
Test your web application on different operating systems like Windows, Unix, MAC, Linux, Solaris with different OS flavors.
Mobile browsing:
This is new technology age. So in future Mobile browsing will rock. Test your web pages on mobile browsers. Compatibility issues may be there on mobile.
Printing options:
If you are giving page-printing options then make sure fonts, page alignment, page graphics getting printed properly. Pages should be fit to paper size or as per the size mentioned in printing option.
5) Performance testing:
Web application should sustain to heavy load. Web performance testing should include:
Web Load Testing
Web Stress Testing
Test application performance on different internet connection speed.
In web load testing test if many users are accessing or requesting the same page. Can system sustain in peak load times? Site should handle many simultaneous user requests, large input data from users, Simultaneous connection to DB, heavy load on specific pages etc.
Stress testing: Generally stress means stretching the system beyond its specification limits. Web stress testing is performed to break the site by giving stress and checked how system reacts to stress and how system recovers from crashes.
Stress is generally given on input fields, login and sign up areas.
In web performance testing web site functionality on different operating systems, different hardware platforms is checked for software, hardware memory leakage errors,
6) Security Testing:
Following are some test cases for web security testing:
Test by pasting internal url directly into browser address bar without login. Internal pages should not open.
If you are logged in using username and password and browsing internal pages then try changing url options directly. I.e. If you are checking some publisher site statistics with publisher site ID= 123. Try directly changing the url site ID parameter to different site ID which is not related to logged in user. Access should denied for this user to view others stats.
Try some invalid inputs in input fields like login username, password, input text boxes. Check the system reaction on all invalid inputs.
Web directories or files should not be accessible directly unless given download option.
Test the CAPTCHA for automates scripts logins.
Test if SSL is used for security measures. If used proper message should get displayed when user switch from non-secure http:// pages to secure https:// pages and vice versa.
All transactions, error messages, security breach attempts should get logged in log files somewhere on web server.
Absolute, Relative, Fixed Positioning: How Do They Differ?
Short answer: Yes, there is one more, "static", which is the default. Yes, they majorly differ. Each of them is incredibily useful and which you should use of course depends on the desired result. Also, don't forget about float, which is an important part of positioning.
Medium answer: I'm not going to do a "long answer" because there is no need to rewrite what has been written many times before, but I will do a "medium answer" here were we can quickly run through each type. I also sometime refer people to this 10 step tutorial, which does a pretty good job of explaining it.
An important concept to understand first is that every single element on a web page is a block. Literally a rectangle of pixels. This is easy to understand when when you set the element to display: block; or if that element is by default display: block; This means you can set a width and a height and that element will respect that. But elements that are display: inline, like a span by default, are also rectangles, they just flow onto the page different, lining up horizontally as they can.
Now that you are picturing every single page element as a block of pixels, we can talk about how positioning is used to get the blocks of pixels exactly where you want them to go. We're going to leave off any discussion of the box model, but that factors into this as well...
Static. This is the default for every single page element. Different elements don't have different default values for positioning, they all start out as static. Static doesn't mean much, it just means that the element will flow into the page as it normally would. The only reason you would ever set an element to position: static is to forcefully-remove some positioning that got applied to an element outside of your control. This is fairly rare, as positioning doesn't cascade.
Relative. This type of positioning is probably the most confusing and misused. What it really means is "relative to itself". If you set position: relative; on an element but no other positioning attributes (top, left, bottom or right), it will no effect on it's positioning at all, it will be exactly as it would be if you left it as position: static; But if you DO give it some other positioning attribute, say, top: 10px;, it will shift it's position 10 pixels DOWN from where it would NORMALLY be. I'm sure you can imagine, the ability to shift an element around based on it's regular position is pretty useful. I find myself using this to line up form elements many times that have a tendency to not want to line up how I want them to.
There are two other things that happen when you set position: relative; on an element that you should be aware of. One is that it introduces the ability to use z-index on that element, which doesn't really work with statically positioned elements. Even if you don't set a z-index value, this element will now appear on top of any other statically positioned element. You can't fight it by setting a higher z-index value on a statically positioned element. The other thing that happens is it limits the scope of absolutely positioned child elements. Any element that is a child of the relatively positioned element can be absolutely positioned within that block. This brings up some powerful opportunities which I talk about here.
Absolute. This is a very powerful type of positioning that allows you to literally place any page element exactly where you want it. You use the positioning attributes top, left bottom and right to set the location. Remember that these values will be relative to the next parent element with relative (or absolute) positioning. If there is no such parent, it will default all the way back up to the element itself meaning it will be placed relatively to the page itself.
The trade-off, and most important thing to remember, about absolute positioning is that these elements are removed from the flow of elements on the page. An element with this type of positioning is not affected by other elements and it doesn't affect other elements. This is a serious thing to consider every time you use absolute positioning. It's overuse or improper use can limit the flexibility of your site.
Fixed. This type of positioning is fairly rare but certainly has its uses. A fixed position element is positioned relative to the viewport, or the browser window itself. The viewport doesn't change when the window is scrolled, so a fixed positioned element will stay right where it is when the page is scrolled, creating an effect a bit like the old school "frames" days. Take a look at this site, where the left sidebar is fixed. This site is a perfect example for since it exhibits both good and bad traits of fixed positioning. The good is that it keeps the navigation present at all times on the page and it creates and interested effect on the page. The bad is that there are some usability concerns. On my smallish laptop, the content in the sidebar is cut off and there is no way from me to scroll down to see the rest of that content. Also if I scroll all the way down to the footer, it overlaps the footer content not allowing me to see all of that. Cool effect, can be useful, but needs to be thoroughly tested.
Medium answer: I'm not going to do a "long answer" because there is no need to rewrite what has been written many times before, but I will do a "medium answer" here were we can quickly run through each type. I also sometime refer people to this 10 step tutorial, which does a pretty good job of explaining it.
An important concept to understand first is that every single element on a web page is a block. Literally a rectangle of pixels. This is easy to understand when when you set the element to display: block; or if that element is by default display: block; This means you can set a width and a height and that element will respect that. But elements that are display: inline, like a span by default, are also rectangles, they just flow onto the page different, lining up horizontally as they can.
Now that you are picturing every single page element as a block of pixels, we can talk about how positioning is used to get the blocks of pixels exactly where you want them to go. We're going to leave off any discussion of the box model, but that factors into this as well...
Static. This is the default for every single page element. Different elements don't have different default values for positioning, they all start out as static. Static doesn't mean much, it just means that the element will flow into the page as it normally would. The only reason you would ever set an element to position: static is to forcefully-remove some positioning that got applied to an element outside of your control. This is fairly rare, as positioning doesn't cascade.
Relative. This type of positioning is probably the most confusing and misused. What it really means is "relative to itself". If you set position: relative; on an element but no other positioning attributes (top, left, bottom or right), it will no effect on it's positioning at all, it will be exactly as it would be if you left it as position: static; But if you DO give it some other positioning attribute, say, top: 10px;, it will shift it's position 10 pixels DOWN from where it would NORMALLY be. I'm sure you can imagine, the ability to shift an element around based on it's regular position is pretty useful. I find myself using this to line up form elements many times that have a tendency to not want to line up how I want them to.
There are two other things that happen when you set position: relative; on an element that you should be aware of. One is that it introduces the ability to use z-index on that element, which doesn't really work with statically positioned elements. Even if you don't set a z-index value, this element will now appear on top of any other statically positioned element. You can't fight it by setting a higher z-index value on a statically positioned element. The other thing that happens is it limits the scope of absolutely positioned child elements. Any element that is a child of the relatively positioned element can be absolutely positioned within that block. This brings up some powerful opportunities which I talk about here.
Absolute. This is a very powerful type of positioning that allows you to literally place any page element exactly where you want it. You use the positioning attributes top, left bottom and right to set the location. Remember that these values will be relative to the next parent element with relative (or absolute) positioning. If there is no such parent, it will default all the way back up to the element itself meaning it will be placed relatively to the page itself.
The trade-off, and most important thing to remember, about absolute positioning is that these elements are removed from the flow of elements on the page. An element with this type of positioning is not affected by other elements and it doesn't affect other elements. This is a serious thing to consider every time you use absolute positioning. It's overuse or improper use can limit the flexibility of your site.
Fixed. This type of positioning is fairly rare but certainly has its uses. A fixed position element is positioned relative to the viewport, or the browser window itself. The viewport doesn't change when the window is scrolled, so a fixed positioned element will stay right where it is when the page is scrolled, creating an effect a bit like the old school "frames" days. Take a look at this site, where the left sidebar is fixed. This site is a perfect example for since it exhibits both good and bad traits of fixed positioning. The good is that it keeps the navigation present at all times on the page and it creates and interested effect on the page. The bad is that there are some usability concerns. On my smallish laptop, the content in the sidebar is cut off and there is no way from me to scroll down to see the rest of that content. Also if I scroll all the way down to the footer, it overlaps the footer content not allowing me to see all of that. Cool effect, can be useful, but needs to be thoroughly tested.
Sunday, September 18, 2011
HTML 4 Deprecated Elements Features
HTML 4 Deprecated Features
A number of elements and attributes are deprecated in HTML 4 as an indication that other methods of accomplishing the same task are preferred. Deprecated features may become obsolete in future versions of HTML, though browsers that support the features will likely continue to support them. Deprecated features are included in HTML 4 Transitional and HTML 4 Frameset but not HTML 4 Strict.
Many presentational elements and attributes are deprecated in favor of style sheets, which allow authors to suggest a presentation with more flexibility and without sacrificing accessibility. Presentational attributes that cannot currently be replaced with style sheets are in most cases not deprecated.
The following elements are deprecated in favor of style sheets:
BASEFONT - Base font change
CENTER - Centered block
FONT - Font change
S - Strike-through text
STRIKE - Strike-through text
U - Underlined text
The following elements are also deprecated:
APPLET - Java applet (deprecated in favor of OBJECT)
DIR - Directory list (deprecated in favor of UL)
ISINDEX - Input prompt (deprecated in favor of INPUT)
MENU - Menu list (deprecated in favor of UL)
A number of elements and attributes are deprecated in HTML 4 as an indication that other methods of accomplishing the same task are preferred. Deprecated features may become obsolete in future versions of HTML, though browsers that support the features will likely continue to support them. Deprecated features are included in HTML 4 Transitional and HTML 4 Frameset but not HTML 4 Strict.
Many presentational elements and attributes are deprecated in favor of style sheets, which allow authors to suggest a presentation with more flexibility and without sacrificing accessibility. Presentational attributes that cannot currently be replaced with style sheets are in most cases not deprecated.
The following elements are deprecated in favor of style sheets:
BASEFONT - Base font change
CENTER - Centered block
FONT - Font change
S - Strike-through text
STRIKE - Strike-through text
U - Underlined text
The following elements are also deprecated:
APPLET - Java applet (deprecated in favor of OBJECT)
DIR - Directory list (deprecated in favor of UL)
ISINDEX - Input prompt (deprecated in favor of INPUT)
MENU - Menu list (deprecated in favor of UL)
HTML 4 - DOCTYPE - Document Type Declaration
DOCTYPE - Document Type Declaration
Each HTML document must begin with a document type declaration that declares which version of HTML the document adheres to. HTML 4 comes in three flavors, each with a different DOCTYPE:
HTML 4 Strict
HTML 4 Strict is a trimmed down version of HTML 4 that emphasizes structure over presentation. Deprecated elements and attributes (including most presentational attributes), frames, and link targets are not allowed in HTML 4 Strict. By writing to HTML 4 Strict, authors can achieve accessible, structurally rich documents that easily adapt to style sheets and different browsing situations. However, HTML 4 Strict documents may look bland on very old browsers that lack support for style sheets.
The document type declaration for HTML 4.01 Strict is
"http://www.w3.org/TR/html4/strict.dtd">
Newer browsers such as Internet Explorer 5 for Mac, Netscape 6, and Mozilla use a standards-compliant rendering for HTML 4 Strict documents. These browsers use a "quirks" mode for most other document types to emulate rendering bugs in older browsers.
HTML 4 Transitional
HTML 4 Transitional includes all elements and attributes of HTML 4 Strict but adds presentational attributes, deprecated elements, and link targets.
The document type declaration for HTML 4.01 Transitional is
"http://www.w3.org/TR/html4/loose.dtd">
Newer browsers such as Internet Explorer 5 for Mac, Netscape 6, and Mozilla use a standards-compliant rendering for HTML 4.01 Transitional documents that include the URI of the DTD in the DOCTYPE. These browsers use a "quirks" mode to emulate rendering bugs in older browsers if the URI is omitted:
HTML 4 Frameset
HTML 4 Frameset is a variant of HTML 4 Transitional for documents that use frames. The FRAMESET element replaces the BODY in a Frameset document.
The document type declaration for HTML 4.01 Frameset is
"http://www.w3.org/TR/html4/frameset.dtd">
Each HTML document must begin with a document type declaration that declares which version of HTML the document adheres to. HTML 4 comes in three flavors, each with a different DOCTYPE:
HTML 4 Strict
HTML 4 Strict is a trimmed down version of HTML 4 that emphasizes structure over presentation. Deprecated elements and attributes (including most presentational attributes), frames, and link targets are not allowed in HTML 4 Strict. By writing to HTML 4 Strict, authors can achieve accessible, structurally rich documents that easily adapt to style sheets and different browsing situations. However, HTML 4 Strict documents may look bland on very old browsers that lack support for style sheets.
The document type declaration for HTML 4.01 Strict is
"http://www.w3.org/TR/html4/strict.dtd">
Newer browsers such as Internet Explorer 5 for Mac, Netscape 6, and Mozilla use a standards-compliant rendering for HTML 4 Strict documents. These browsers use a "quirks" mode for most other document types to emulate rendering bugs in older browsers.
HTML 4 Transitional
HTML 4 Transitional includes all elements and attributes of HTML 4 Strict but adds presentational attributes, deprecated elements, and link targets.
The document type declaration for HTML 4.01 Transitional is
"http://www.w3.org/TR/html4/loose.dtd">
Newer browsers such as Internet Explorer 5 for Mac, Netscape 6, and Mozilla use a standards-compliant rendering for HTML 4.01 Transitional documents that include the URI of the DTD in the DOCTYPE. These browsers use a "quirks" mode to emulate rendering bugs in older browsers if the URI is omitted:
HTML 4 Frameset
HTML 4 Frameset is a variant of HTML 4 Transitional for documents that use frames. The FRAMESET element replaces the BODY in a Frameset document.
The document type declaration for HTML 4.01 Frameset is
"http://www.w3.org/TR/html4/frameset.dtd">
CSS Interview Questions
What is a z-index?
Z-index is a CSS property that sets the stack order of specific elements. An element with greater stack order is always in front of an element with a lower stack order.
Explain how you solved some css problem?
You should be able to explain a CSS bug that you worked on and how you went about solving it. You could talk about IE issues, take a look at these CSS problems that often need solutions for Internet Explorer.
Explain the benefits of CSS sprites?
Most importantly there is a performance benefit as CSS sprites reduce page load time by minimizing HTTP requests for different images. Usually there is also an accessibility benefit as the code degrades gracefully and shows text to screen readers, search engines, and browsers without CSS. I also think that CSS sprites are easier to manage as you are working with one image instead of many small images. Finally, you should also know how to implement CSS sprites.
Z-index is a CSS property that sets the stack order of specific elements. An element with greater stack order is always in front of an element with a lower stack order.
Explain how you solved some css problem?
You should be able to explain a CSS bug that you worked on and how you went about solving it. You could talk about IE issues, take a look at these CSS problems that often need solutions for Internet Explorer.
Explain the benefits of CSS sprites?
Most importantly there is a performance benefit as CSS sprites reduce page load time by minimizing HTTP requests for different images. Usually there is also an accessibility benefit as the code degrades gracefully and shows text to screen readers, search engines, and browsers without CSS. I also think that CSS sprites are easier to manage as you are working with one image instead of many small images. Finally, you should also know how to implement CSS sprites.
Javascript QA
What is the main difference between window.onload and onDocumentReady?
Both functions are used to perform tasks when the page is loaded in the browser but they have important differences. Most importantly, “window.onload” will execute code when browser has loaded the DOM tree and all other resources like images, objects, etc, while onDocumentReady allows you to execute code when only the DOM tree has been built, without waiting for images to load. Thus, you can start scripting agains the DOM much quicker with onDocumentReady. Another important difference is that window.onload is not cross-browser compatible while using something like jQuery’s document.ready() will work nicely on all browsers.
What is the difference between undefined value and null value?
In JavaScript, undefined means that a value has been declared but has not yet been assigned a value, such as null, which can be assigned to a variable as a representation of no value. If a value is null, it was assigned programmatically, as JavaScript never sets a value to null on its own. Also, undefined and null are two different types: null is an object while undefined is a type itself (undefined).
Explain the difference between synchronous and asynchronous JS request?
Most importantly, synchronous request blocks JavaScript engine until the interaction with the server is complete. The user cannot click away, cancel request, or go to another tab during this time. It is bad for user experience and that is why we have AsynchronousJAX.
Explain briefly the difference between normal array and associative arrays?
This kind of a question could be rephrased as “explain the difference between a['one']=’dog’ and a[one]=’dog’” because the main difference between a normal array in JavaScript and associative arrays is that associative arrays use Strings instead of Integer numbers as index. But this is also kind of a trick question as JavaScript does not support associative arrays, they are objects and not really an array
Prototype inheritance vs Classic inheritance
Closure.
Why extending built in JavaScript objects (like how Prototype library does) is not a good idea.
Difference between document load event vs document ready event.
What are the different JavaScript frameworks you have used. And more importantly, which library do you prefer and why?
Event delegation
Cross Browser Scripting a. What is browser detection? What is feature detection? Which one is preferred?
Optimizing JavaScript heavy pages
Some sort of code test.
Both functions are used to perform tasks when the page is loaded in the browser but they have important differences. Most importantly, “window.onload” will execute code when browser has loaded the DOM tree and all other resources like images, objects, etc, while onDocumentReady allows you to execute code when only the DOM tree has been built, without waiting for images to load. Thus, you can start scripting agains the DOM much quicker with onDocumentReady. Another important difference is that window.onload is not cross-browser compatible while using something like jQuery’s document.ready() will work nicely on all browsers.
What is the difference between undefined value and null value?
In JavaScript, undefined means that a value has been declared but has not yet been assigned a value, such as null, which can be assigned to a variable as a representation of no value. If a value is null, it was assigned programmatically, as JavaScript never sets a value to null on its own. Also, undefined and null are two different types: null is an object while undefined is a type itself (undefined).
Explain the difference between synchronous and asynchronous JS request?
Most importantly, synchronous request blocks JavaScript engine until the interaction with the server is complete. The user cannot click away, cancel request, or go to another tab during this time. It is bad for user experience and that is why we have AsynchronousJAX.
Explain briefly the difference between normal array and associative arrays?
This kind of a question could be rephrased as “explain the difference between a['one']=’dog’ and a[one]=’dog’” because the main difference between a normal array in JavaScript and associative arrays is that associative arrays use Strings instead of Integer numbers as index. But this is also kind of a trick question as JavaScript does not support associative arrays, they are objects and not really an array
Prototype inheritance vs Classic inheritance
Closure.
Why extending built in JavaScript objects (like how Prototype library does) is not a good idea.
Difference between document load event vs document ready event.
What are the different JavaScript frameworks you have used. And more importantly, which library do you prefer and why?
Event delegation
Cross Browser Scripting a. What is browser detection? What is feature detection? Which one is preferred?
Optimizing JavaScript heavy pages
Some sort of code test.
Saturday, September 17, 2011
Javascript
Mastering Javascript Arrays
Believe it or not, the very first version of Javascript shipped without Arrays. Subsequent versions made up for the oversight and modern Javascript Arrays are powerful structures indeed, even emulating many common data structures such as stacks and queues. This reference will cover the core functionality of Arrays as well as introduce a few useful extensions.
Introduction
An Array is an enumerated list of variables. It's a programming construct that allows programmers to replace this…
x0=0;
x1=1;
x2=2;
x3=3;
x4=4;
x5=5;
…with this…
x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
The index (the number in the brackets [] )can be referenced by a variable, allowing for easy looping through the data structure.
for(i=0; i<6; i++) {
document.writeln(x[i]+'
);
}
Which will output the following…
0
1
2
3
4
5
Creating A New Array
Most tutorials start out introducing you to arrays as such…
var myArray = new Array(10);
Current best-practice eschews the new keyword on Javascript primitives. If you want to create a new Array simply use brackets [] like this…
var myArray = [];
You don't need to tell Javascript how many items to size the Array for. Javascript will automatically increase the size of the Array as needed, as you add items into the Array. Creating an Array with brackets instead of with the new constructor avoids a bit of confusion where you want to initialize only one integer. For instance.
var badArray = new Array(10); // Creates an empty Array that's sized for 10 elements.
var goodArray= [10]; // Creates an Array with 10 as the first element.
As you can see these two lines do two very different things. If you had wanted to add more than one item then badArray would be initialized correctly since Javascript would then be smart enough to know that you were initializing the array instead of stating how many elements you wanted to add.
Since the new constructor is not necessary with Arrays and there's a slight chance of unintended results by using the new constructor, it's recommended you not use new Array() to create an Array.
Initializing An Array
You can initialize your array with pre-defined data…
var myArray = ['January', 'February', 'March'];
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>March
You can inizialize your array with data after an empty array has been created…
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray[2] = 'March';
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>March
If you skip an element, the blank Array elements will be of type undefined
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray[5] = 'March';
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>undefined
document.writeln('3>'+myArray[3]+'
'); // Will output: 3>undefined
document.writeln('4>'+myArray[4]+'
'); // Will output: 4>undefined
document.writeln('5>'+myArray[5]+'
'); // Will output: 5>March
Storing Data In An Array
An array can store anything you can assign to a variable: booleans, numbers, strings, functions, objects, other Arrays, even regular expressions…
var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ];
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>3
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>hello!
document.writeln('2>'+myArray[2]()+'
'); // Will output: 2>5
document.writeln('3>'+myArray[3].color+'
'); // Will output: 3>blue
document.writeln('3>'+myArray[3].budget+'
'); // Will output: 3>25
document.writeln('4>'+myArray[4].test(myArray[1])+'
'); // Will output: 4>true
Multi-Dimensional Arrays
Since an Array can store other Arrays you can get the benefit of multi-dimension arrays.
var x=[0,1,2,3,4,5];
var y=[x];
In the above example we created an array named x and assigned it as the first element in the array y. If we ask for the value of y[0] it will return the contents of x as a string because we didn't specify an index.
var x=[0,1,2,3,4,5];
var y=[x];
document.writeln(y[0]); // Will output: 0,1,2,3,4,5
If we wanted the third index we'd access it this way…
var x=[0,1,2,3,4,5];
var y=[x];
document.writeln(y[0][3]); // Will output: 2
There's no defined limit to how many Arrays you can nest in this manner. For instance …
document.writeln(bigArray[5][8][12][1])
…would indicate bigArray's 5th index held an array, who's 8th index held an array, who's 12th index held an array, who's first index contains the data we want.
Javascript Arrays Are Passed By Reference
Arrays are passed to functions by reference, or as a pointer to the original. This means anything you do to the Array inside the function affects the original.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
document.writeln(myArray[1]); // Will output: one
function passedByReference(refArray) {
refArray[1] = 'changed';
}
passedByReference(myArray);
document.writeln(myArray[1]); // Will output: changed
Javascript Arrays Are Assigned By Reference
Assigning an Array to a new variable creates a pointer to the original Array. For instance…
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var newArray= myArray;
newArray[1] = 'changed';
document.writeln(myArray[1]); // Will output: changed
Passing Arrays As Values
To pass an Array by value instead of by reference, use the Array.slice() method.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var newArray= myArray.slice();
newArray[1] = 'changed';
document.writeln(myArray[1]); // Will output: one
function passedByReference(refArray) {
refArray[1] = 'changed';
}
passedByReference(myArray.slice());
document.writeln(myArray[1]); // Will output: one
Array.length
Every Array has a length property. This always contains the number of elements in the array. Since Arrays always start at zero, the length property is convenient for loops since it will always be one greater than the actual index. For instance if the Array has 10 elements then the indexes will be 0-9, so as long as our counter is less than the Array.length we'll cover the entire Array…
for (var i=0; i Going back to our undefined example above. Even though 3 of the Array items are undefined the length property will still count them because it's always one higher than the highest accessable index value.
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray[5] = 'March';
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>undefined
document.writeln('3>'+myArray[3]+'
'); // Will output: 3>undefined
document.writeln('4>'+myArray[4]+'
'); // Will output: 4>undefined
document.writeln('5>'+myArray[5]+'
'); // Will output: 5>March
document.writeln('Array Length: '+myArray.length); // Will output: Array Length: 6
Array.length is NOT a read-only value, you can set it as you wish. If you have 100 elements in an array and set the length to 50, Javascript will truncate the last 50 elements from the array (effectively deleting them). If you have 10 elements in an array and set Array.length to 100 then the length of the array will be expanded to 100, creating 90 undefined elements after the original 10 items.
Javascript Does Not Support Associative Arrays
An associative array is an array which uses a string instead of a number as an index.
var normalArray = [];
normalArray[1] = 'This is an enumerated array';
alert(normalArray[1]); // outputs: This is an enumerated array
var associativeArray = [];
associativeArray['person'] = 'John Smith';
alert(associativeArray['person']); // outputs: John Smith
Javascript does not have, and does not support Associative Arrays. However… All arrays in Javascript are objects and Javascript's object syntax gives a basic emulation of an associative Array. For this reason the example code above will actually work. Be warned that this is not a real array and it has real pitfals if you try to use it. The 'person' element in the example becomes part of the Array object's properties and methods, just like .length, .sort(), .splice(), and all the other built-in properties and methods.
You can loop through an object's properties with the following loop…
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
for (i in associativeArray) {
document.writeln(i+':'+associativeArray[i]+', ');
// outputs: one:First, two:Second, three:Third
};
In the above example, associativeArray.length will be zero because we didn't actually put anything into the Array, we put it into associativeArray's object. associativeArray[0] will be undefined.
The loop in the above example will also pick up any methods, properties, and prototypes which have been added to the array and not just your data. A lot of problems people have with the Prototype library is that their associative arrays break because Prototype adds a few useful Prototype functions to the Array object and for i in x loops pick up those additional methods. That's the pitfal of using Array/objects as a poor man's associative array.
As a final example, the previous code will work regardless of whether you define associativeArray as an Array ([]), an Object({}), a Regular Expression (//), String(""), or any other Javascript object.
The bottom line is -- don't try to use associative arrays, code for what they are -- object properties, not Arrays.
Array Methods Reference
Since Javascript Arrays are modified objects, each and every Array you create has a few core methods. What's really interesting is that some of these methods implement basic data structures you'd normally have to write yourself such as stacks (push, pop) and queues (shift, unshift).
Method IE Version Mozilla Version Notes
concat 4.0 4.0 Joins multiple Arrays
every * FF 1.5 Calls a function for every element of the array until false is returned.
filter * FF 1.5 Creates an array with each element which evaluates true in the function provided.
forEach * FF 1.5 Executes a specified function on each element of an Array
join 3.0 3.0 Joins all the Array elements together into a string.
indexOf * FF 1.5 Searches the Array for specific elements.
lastIndexOf * FF 1.5 Returns the last item in the Array which matches the search critera.
map * FF 1.5 Creates a new array with the result of calling the specified function on each element of the Array.
pop 5.5 4.0 Returns the last item in the Array and removes it from the Array.
push 5.5 4.0 Adds the item to the end of the Array.
reverse 3.0 3.0 Reverses the Array so the last item becomes the first and vice-versa.
shift 5.5 4.0 Returns the first item in the Array and removes it from the Array.
slice 4.0 4.0 Returns a new array from the specified index and length.
some * FF 1.5 Passes each element through the supplied function until true is returned.
sort 3.0 3.0 Sorts the array alphabetically or by the supplied function.
splice 5.5 4.0 Deletes the specified index(es) from the Array.
toSource --- FF 1.5 Returns the source code of the array.
toString 3.0 3.0 Returns the Array as a string.
unshift 5.5 4.0 Inserts the item(s) to the beginning of the Array.
valueOf 3.0 3.0 Like toString, returns the Array as a string.
* Prototype functions are available to make this method available to Internet Explorer and older browsers.
Array.concat(value1[value2[value...]])
The concat method appends the passed values to the end of the Array, passing back a NEW array containing the joined values. The values passed to the concat method can be anything you can assign to a variable in Javascript.
var myArray = [1,2,3];
var newArray= [4,5,6];
var seven = 7;
var eight = 'eight';
var nine = {'sky':'blue', 'grass':'green'};
var joinedArray=myArray.concat(newArray, seven, eight, nine);
document.writeln(myArray); // outputs: 1,2,3
document.writeln(joinedArray); // outputs: 1,2,3,4,5,6,7,'eight',[object Object]
Supported Since: Netscape 4.0, IE 4.0
Array.every(function)
The every method is a Firefox method which accepts a function as an argument. Every value of the array is passed to that function until the function returns false. If no elements return false then every will return true, if an element returned false then every will return false. It's a convenient way to test an Array and see if every element is a number for instance.
This method will pass the current value, the current index, and a pointer to the array to your function. myfunction(curValue, curIndex, curArray)
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
document.writeln(myArray.every(isNumeric)); // outputs: true
var myArray = [1,2,3,4,5,6,7,8,9,'ten',11,12,13,14,15];
document.writeln(myArray.every(isNumeric)); // outputs: false
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .every() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.filter(function)
Filter creates a new Array of items which evaluate to true in the supplied function. In the Array.every() method, we tested if the entire Array was composed of Numbers. In Array.filter() we can extract all the numbers, creating a new Array in the process.
This method will pass the current value, the current index, and a pointer to the array to your function. myfunction(curValue, curIndex, curArray)
Here we pass the array through the same function as .every() -- isNumeric -- and if the element is a number it's placed in the new oddArray Array.
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var oddArray=myArray.filter(isNumeric);
document.writeln(oddArray); // outputs: 1,3,5,7,9
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .filter() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.forEach(function)
This is an odd little method. All it does is pass each element of the Array to the passed function. It ignores any results from the function and it returns nothing itself. It will pass all the Array contents through the function of your choice but the Array itself will not be affected and it will return nothing by itself.
This method will pass the current value, the current index, and a pointer to the array to your function. myfunction(curValue, curIndex, curArray)
var printArray = function (x, idx) {
document.writeln('['+idx+'] = '+x);
}
var myArray = [1,'two',3,'four',5];
myArray.forEach(printArray); // outputs: [0] = 1 [1] = two [2] = 3 [3] = four [4] = 5
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .forEach() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.join(delimeter)
The join method will output your Array as a string with a delimiter of your choice. This is a very useful function if you need to convert an Array into something you can send back to the server. Simply pick a unique delimiter which is not likely to appear inside the data in your Array then you can turn it back into an Array on the server side.
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var test1 = myArray.join();
var test2 = myArray.join(', ');
var test3 = myArray.join('+');
document.writeln(test1+'
'); // outputs: 1,two,3,four,5,six,7,eight,9,ten
document.writeln(test2+'
'); // outputs: 1, two, 3, four, 5, six, 7, eight, 9, ten
document.writeln(test3+'
'); // outputs: 1+two+3+four+5+six+7+eight+9+ten
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.indexOf(searchStr[, startIndex])
The indexOf method will search the array until it matches your search critera. It will then return the index where the item was found. It will match only one item and the match must be exact. This is not as useful as the custom .find() method provided below in the Useful Prototypes section.
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
document.writeln(myArray.indexOf('six')); // outputs: 5
document.writeln(myArray.indexOf('not here')); // outputs: -1
To find and return all occurrences of an item you can use the following code…
var foundItems = [];
var index = array.indexOf(element)
while (index != -1)
{
foundItems.push(index);
index = array.indexOf(element, ++index);
}
This will create an array of indexes which match your search criteria (element) and store them in foundItems[].
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .indexOf() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.lastIndexOf(searchStr[, startIndex])
Array.indexOf() searches from first to last, lastIndexOf searches from last to first.
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,5,'ten'];
document.writeln(myArray.lastIndexOf(5)); // outputs: 9
document.writeln(myArray.lastIndexOf('not here')); // outputs: -1
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .lastIndexOf() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]);
if (isNaN(from))
{
from = len - 1;
}
else
{
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
else if (from >= len)
from = len - 1;
}
for (; from > -1; from--)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.map(function)
The map method will call the provided function for each value of the array and it will return an array containing the results of those function calls.
The callback function is called with three arguments: the value, the index, and a pointer to the array being used respectively.
In the following example each element of the array is tested to see if it is numeric, if it is, it's passed into the new array, otherwise a zero is inserted.
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var testElement = function(x) {
if (isNumeric(x)) {
return x;
} else {
return 0;
}
}
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var newArray= myArray.map(testElement);
document.writeln(newArray); // outputs: 1,0,3,0,5,0,7,0,9,0
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .map() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.pop()
The pop() method implements a basic stack structure in Javascript Arrays. Array.pop() will return the last element of an Array and delete it from the Array.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
document.writeln(myArray.length+'
'); // outputs: 10
var popped = myArray.pop();
document.writeln(popped+'
'); // outputs: 10
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9
document.writeln(myArray.length+'
'); // outputs: 9
Supported Since: Netscape 4.0, Internet Explorer: 5.5
Array.push(value[,value2[, value...]])
The push() method adds the passed value(s) to the end of the array. In addition to being incredibly useful for adding items to the array, it also allows the Array to emulate a basic stack structure.
var myArray = [1,2,3,4,5];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5
document.writeln(myArray.length+'
'); // outputs: 5
myArray.push(6);
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6
document.writeln(myArray.length+'
'); // outputs: 6
myArray.push(7,8,9,10);
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
document.writeln(myArray.length+'
'); // outputs: 10
Supported Since: Netscape 4.0, Internet Explorer: 5.5
Array.reverse()
The reverse() method takes the array and reverses the order so the first item becomes the last and the last item becomes the first.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
myArray.reverse();
document.writeln(myArray+'
'); // outputs: 10,9,8,7,6,5,4,3,2,1
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.shift()
The shift() method returns the first item in the Array, removing it from the Array in the process. Together with Array.unshift, Shift implements a basic queue structure in Javascript Arrays.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
theItem = myArray.shift();
document.writeln(theItem+'
'); // outputs: 1
document.writeln(myArray+'
'); // outputs: 2,3,4,5,6,7,8,9,10
Supported Since: Netscape 5.5, Internet Explorer: 4.0
Array.slice([begin[, end]])
The slice() method copies a block of the array and returns it to your new variable. If you don't specify a beginning index the slice will begin at zero. If you don't specify and ending index the splice will continue to the end of the Array. So to make a copy of the array simply don't pass any arguments to the method.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
var newArray = myArray.slice();
document.writeln(newArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
var newArray = myArray.slice(5);
document.writeln(newArray+'
'); // outputs: 6,7,8,9,10
var newArray = myArray.slice(5,7);
document.writeln(newArray+'
'); // outputs: 6,7
Supported Since: Netscape 4.0, Internet Explorer: 4.0
Array.some(function)
The some() method will pass each element of the Array through the supplied function until true has been returned. If the function returns true some will in turn return true. If the entire array has been traversed and no true condition was found then some() will return false.
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var myArray = ['one', 'two', 'three', 'four', 'five'];
document.writeln(myArray.some(isNumeric)); // outputs: false
var myArray = ['one', 'two', 3, 'four', 'five'];
document.writeln(myArray.some(isNumeric)); // outputs: true
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .some() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
fun.call(thisp, this[i], i, this))
return true;
}
return false;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.sort([function])
The sort() method, by default, will sort an Array alphabetically. If you would like to create your own sorting criteria, supply a function for the sort method to call. Sort will pass your function (a,b). If a is less than b then return -1, if a is equal to b then return 0, if a is greater than b then return 1. Sort will take it from there.
var myArray=[8,10,50,5,7,83,24,19,168];
myArray.sort()
document.writeln(myArray); // 10,168,19,24,5,50,7,8,83 (sorted alphabetically)
myArray.sort( function (a,b) { return a-b }); // Sort Numerically
document.writeln(myArray); //5,7,8,10,19,24,50,83,168
function compare(a, b) {
// psudeo code.
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
if (a == b) {
return 0;
}
}
myArray.sort(compare);
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.splice(start[, howmany[, element1[,element...]]])
The splice() method at it's most basic allows you to delete an element from the array by simply specifying the index you'd like to delete and then how many elements you'd like to delete from that point. You can also specify any number of elements to insert into the array at that point.
splice() returns a new array containing the removed items. If you specify a starting number but don't specify how many, splice will truncate the array.
You can insert elements into the array without deleting anything by specifying zero for howmany.
var myArray=[1,2,3,4,5,6,7,8,9,10];
var newArray=[];
//delete one item at the 5th index.
newArray = myArray.splice(5,1);
document.writeln(myArray); // outputs: 1,2,3,4,5,7,8,9,10
document.writeln(newArray); // outputs 6
//truncate the array at the 5th index.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(5);
document.writeln(myArray); // outputs: 1,2,3,4,5
document.writeln(newArray); // outputs 6,7,8,9,10
// do nothing at all.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice();
document.writeln(myArray); // outputs: 1,2,3,4,5,6,7,8,9,10
document.writeln(newArray); // outputs undefined
// cut out the middle and insert 'blue', and 'green'
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(1,8, 'blue', 'green');
document.writeln(myArray); // outputs: 1,blue,green,10
document.writeln(newArray); // outputs 2,3,4,5,6,7,8,9
// Insert without deleting.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(5,0, '*');
newArray = myArray.splice(4,0, '*');
document.writeln(myArray); // outputs: 1,2,3,4,*,5,*,6,7,8,9,10
Supported Since: Netscape 4.0, Internet Explorer: 5.5
Array.toSource()
The toSource() method is a Firefox only extension which takes the contents of an Array and returns the source code. That is, if you were to use the toSource() method and pass it through an eval statement you could rebuild the array. This is a useful debugging method and can be useful in Ajax/JSON applications. There is no prototype for this method, it works only in Firefox.
var myArray = ["a", "b", "c", {'sky':'blue', 'grass':'green'}];
var theSource = myArray.toSource()
document.writeln(theSource); // outputs: ["a", "b", "c", {sky:"blue", grass:"green"}]
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.toString()
This method outputs the contents of the Array as a string. It's not as powerful as toSource() since it doesn't expand objects but it is supported by browsers other than firefox.
var myArray = ["a", "b", "c", {'sky':'blue', 'grass':'green'}];
var theSource = myArray.toString()
document.writeln(theSource); // outputs: a,b,c,[object Object]
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.unshift(value1[, value2[, value...]])
The unshift method inserts the value(s) passed in the method's arguments into the start of the Array. Together with the shift(), unshift() implements a basic queue structure in Javascript Arrays.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
myArray.unshift('a','b','c');
document.writeln(myArray+'
'); // outputs: a,b,c,1,2,3,4,5,6,7,8,9,10
Supported Since: Netscape 5.5, Internet Explorer: 4.0
Array.valueOf()
See Array.toString().
Howto Delete An Element From An Array
You can delete an item from an Array with the splice() method. Simply supply the index of the item you wish to delete and how many items you want to delete and the item(s) will be removed for you.
var myArray=[1,2,3,4,5,6,7,8,9,10];
myArray.splice(5,1); //delete one item at the 5th index.
document.writeln(myArray); // outputs: 1,2,3,4,5,7,8,9,10
Howto Easily Add Items To An Array
There are three ways to easily add items to an array. First you can use the Array.length property. Since Arrays start with index 0, then Array.length is always equal to the first empty index at the end of the Array.
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
document.writeln(myArray.length); // Will output: 2
myArray[myArray.length] = 'March'; // Adds Item to end of Array
document.writeln(myArray.length); // Will output: 3
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>March
You can add the .push() method of the Array. This will add the requested items to the end of the Array.
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray.push('March'); // Adds Item to end of Array
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>March
You can use the .unshift() method to insert an item at the BEGINNING of the array!
var myArray = [];
myArray[0] = 'February';
myArray[1] = 'March';
myArray.unshift('January'); // Adds Item to beginning of Array
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>March
Howto Clear-out/Reset An Array
Clearing out or resetting an array is as simple as assigning it a new empty bracket.
var myArray=[1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray); // outputs: 1,2,3,4,5,6,7,8,9,10
myArray = []; // clear-out the array
document.writeln(myArray); // outputs null
Alternatively you can set the length of the array to zero (myArray.length=0), likewise if you just need to clear out a few items at the end of the array, lower the length property by the number of items you would like removed from the end of the array.
Howto Tell The Difference Between An Array And An Object
Because Javascript's Array is just a modified Javascript object, it's actually not that easy to differentiate an Array and an Object, even when you absolutely need to. So here's a little function that will let you ask the array itself what it is. isArray() will return true if it's an array and false if it is not an Array.
function isArray(testObject) {
return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}
Usage…
var tmp = [5,9,12,18,'blue',30,7,97,53,33,30,35,27,30];
var tmp2 = {0:5,1:9,2:12}
test1 = isArray(tmp); // returns true
test2 = isArray(tmp2); // returns false;
Howto Pass An Array Via Ajax
If you have an Array you need to package up and send via Ajax, you need to use the join method to turn your Array into a string. Find a unique character that is unlikely to appear inside your Array and use it as your delimiter. For most applications the tildie (~) character is a safe delimeter to use.
var myArray=[1,2,3,4,5,6,7,8,9,10];
var theData = myArray.join('~'); // theData=1~2~3~4~5~6~7~8~9~10
theData=encodeURIComponent(theData); // Optional but safe! Escape the data
Now just send theData through your ajax routine. On the server just do a split('~') in php to turn it back into an Array.
Howto Receive An Array Via Ajax
On the server side convert the Array into a string using a unique delimiter -- implode in php. (We're assuming a string with a tildie [~] delimiter in this example).
Once you've received the string from your Ajax handler simply use the string's split method to bust the string into an Array.
var ajaxStr = '1~2~3~4~5~6~7~8~9~10';
var myArray = ajaxStr.split('~');
document.writeln(myArray); // outputs: 1,2,3,4,5,6,7,8,9,10
Useful Prototypes
With prototypes you can extend the Array object and include any additional functionality you wish. For instance, the Array.sort() method sorts alphabetically by default but adding a numerical sort is as simple as including the following snippet of code in your toolbox.
Array.prototype.sortNum = function() {
return this.sort( function (a,b) { return a-b; } );
}
All this does is make sortNum a method of Array just like sort and splice and join and all the other default methods. Any array can access it, even arrays that haven't been assigned to variables…
document.writeln([5,8,12,50,25,80,93].sortNum()); // outputs 5,8,12,25,50,80,93
Since the Javascript Array object is already so rich, there's not much left that needs to be done. However, there are a few snippets people have found helpful.
Useful Prototypes: Array.sortNum()
As stated above, just use the sortNum() method when you want to sort an array numerically instead of alphabetically.
Array.prototype.sortNum = function() {
return this.sort( function (a,b) { return a-b; } );
}
Useful Prototypes: Array.find(searchStr)
Array.indexOf() is a nice method but this extension is a little more powerful and flexible. First it will return an array of all the indexes it found (it will return false if it doesn't find anything). Second in addition to passing the usual string or number to look for you can actually pass a regular expression, which makes this the ultimate Array prototype in my book.
Array.prototype.find = function(searchStr) {
var returnArray = false;
for (i=0; i if (typeof(searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
if (this[i]===searchStr) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}
Usage…
var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble'];
// 0/1/2 /3 /4/5 /6 /7 /8 /9/10/11/12/13/14/15/16/17/ 18/ 19/ 20
var thirty=tmp.find(30); // Returns 9, 14, 17
var thirtyfive=tmp.find('35'); // Returns 18
var thirtyfive=tmp.find(35); // Returns 15
var haveBlue=tmp.find('blue'); // Returns 8
var notFound=tmp.find('not there!'); // Returns false
var regexp1=tmp.find(/^b/); // returns 8,20 (first letter starts with b)
var regexp1=tmp.find(/^b/i); // returns 8,19,20 (same as above but ignore case)
Useful Prototypes: Array.shuffle()
The anti-sort, this shuffle() method will take the contents of the array and randomize them. This method is surprisingly useful and not just for shuffling an array of virtual cards.
Array.prototype.shuffle = function (){
for(var rnd, tmp, i=this.length; i; rnd=parseInt(Math.random()*i), tmp=this[--i], this[i]=this[rnd], this[rnd]=tmp);
};
Usage…
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
myArray.shuffle();
document.writeln(myArray); // outputs~: 8,1,13,11,2,3,4,12,6,14,5,7,10,15,9
Useful Prototypes: Array.compare(array)
If you need to be able to compare Arrays this is the prototype to do it. Pass an Array you want to compare and if they are identical the method will return true. If there's a difference it will return false. The match must be identical so '80' is not the same as 80.
Array.prototype.compare = function(testArr) {
if (this.length != testArr.length) return false;
for (var i = 0; i < testArr.length; i++) {
if (this[i].compare) {
if (!this[i].compare(testArr[i])) return false;
}
if (this[i] !== testArr[i]) return false;
}
return true;
}
Usage…
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var yourArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
document.writeln(myArray.compare(yourArray)); // outputs: true;
yourArray[0]='1';
document.writeln(myArray.compare(yourArray)); // outputs: false;
yourArray[0]='one';
document.writeln(myArray.compare(yourArray)); // outputs: false;
yourArray[0]=1;
document.writeln(myArray.compare(yourArray)); // outputs: true;
Ref: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Believe it or not, the very first version of Javascript shipped without Arrays. Subsequent versions made up for the oversight and modern Javascript Arrays are powerful structures indeed, even emulating many common data structures such as stacks and queues. This reference will cover the core functionality of Arrays as well as introduce a few useful extensions.
Introduction
An Array is an enumerated list of variables. It's a programming construct that allows programmers to replace this…
x0=0;
x1=1;
x2=2;
x3=3;
x4=4;
x5=5;
…with this…
x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
The index (the number in the brackets [] )can be referenced by a variable, allowing for easy looping through the data structure.
for(i=0; i<6; i++) {
document.writeln(x[i]+'
);
}
Which will output the following…
0
1
2
3
4
5
Creating A New Array
Most tutorials start out introducing you to arrays as such…
var myArray = new Array(10);
Current best-practice eschews the new keyword on Javascript primitives. If you want to create a new Array simply use brackets [] like this…
var myArray = [];
You don't need to tell Javascript how many items to size the Array for. Javascript will automatically increase the size of the Array as needed, as you add items into the Array. Creating an Array with brackets instead of with the new constructor avoids a bit of confusion where you want to initialize only one integer. For instance.
var badArray = new Array(10); // Creates an empty Array that's sized for 10 elements.
var goodArray= [10]; // Creates an Array with 10 as the first element.
As you can see these two lines do two very different things. If you had wanted to add more than one item then badArray would be initialized correctly since Javascript would then be smart enough to know that you were initializing the array instead of stating how many elements you wanted to add.
Since the new constructor is not necessary with Arrays and there's a slight chance of unintended results by using the new constructor, it's recommended you not use new Array() to create an Array.
Initializing An Array
You can initialize your array with pre-defined data…
var myArray = ['January', 'February', 'March'];
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>March
You can inizialize your array with data after an empty array has been created…
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray[2] = 'March';
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>March
If you skip an element, the blank Array elements will be of type undefined
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray[5] = 'March';
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>undefined
document.writeln('3>'+myArray[3]+'
'); // Will output: 3>undefined
document.writeln('4>'+myArray[4]+'
'); // Will output: 4>undefined
document.writeln('5>'+myArray[5]+'
'); // Will output: 5>March
Storing Data In An Array
An array can store anything you can assign to a variable: booleans, numbers, strings, functions, objects, other Arrays, even regular expressions…
var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ];
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>3
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>hello!
document.writeln('2>'+myArray[2]()+'
'); // Will output: 2>5
document.writeln('3>'+myArray[3].color+'
'); // Will output: 3>blue
document.writeln('3>'+myArray[3].budget+'
'); // Will output: 3>25
document.writeln('4>'+myArray[4].test(myArray[1])+'
'); // Will output: 4>true
Multi-Dimensional Arrays
Since an Array can store other Arrays you can get the benefit of multi-dimension arrays.
var x=[0,1,2,3,4,5];
var y=[x];
In the above example we created an array named x and assigned it as the first element in the array y. If we ask for the value of y[0] it will return the contents of x as a string because we didn't specify an index.
var x=[0,1,2,3,4,5];
var y=[x];
document.writeln(y[0]); // Will output: 0,1,2,3,4,5
If we wanted the third index we'd access it this way…
var x=[0,1,2,3,4,5];
var y=[x];
document.writeln(y[0][3]); // Will output: 2
There's no defined limit to how many Arrays you can nest in this manner. For instance …
document.writeln(bigArray[5][8][12][1])
…would indicate bigArray's 5th index held an array, who's 8th index held an array, who's 12th index held an array, who's first index contains the data we want.
Javascript Arrays Are Passed By Reference
Arrays are passed to functions by reference, or as a pointer to the original. This means anything you do to the Array inside the function affects the original.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
document.writeln(myArray[1]); // Will output: one
function passedByReference(refArray) {
refArray[1] = 'changed';
}
passedByReference(myArray);
document.writeln(myArray[1]); // Will output: changed
Javascript Arrays Are Assigned By Reference
Assigning an Array to a new variable creates a pointer to the original Array. For instance…
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var newArray= myArray;
newArray[1] = 'changed';
document.writeln(myArray[1]); // Will output: changed
Passing Arrays As Values
To pass an Array by value instead of by reference, use the Array.slice() method.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var newArray= myArray.slice();
newArray[1] = 'changed';
document.writeln(myArray[1]); // Will output: one
function passedByReference(refArray) {
refArray[1] = 'changed';
}
passedByReference(myArray.slice());
document.writeln(myArray[1]); // Will output: one
Array.length
Every Array has a length property. This always contains the number of elements in the array. Since Arrays always start at zero, the length property is convenient for loops since it will always be one greater than the actual index. For instance if the Array has 10 elements then the indexes will be 0-9, so as long as our counter is less than the Array.length we'll cover the entire Array…
for (var i=0; i
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray[5] = 'March';
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>undefined
document.writeln('3>'+myArray[3]+'
'); // Will output: 3>undefined
document.writeln('4>'+myArray[4]+'
'); // Will output: 4>undefined
document.writeln('5>'+myArray[5]+'
'); // Will output: 5>March
document.writeln('Array Length: '+myArray.length); // Will output: Array Length: 6
Array.length is NOT a read-only value, you can set it as you wish. If you have 100 elements in an array and set the length to 50, Javascript will truncate the last 50 elements from the array (effectively deleting them). If you have 10 elements in an array and set Array.length to 100 then the length of the array will be expanded to 100, creating 90 undefined elements after the original 10 items.
Javascript Does Not Support Associative Arrays
An associative array is an array which uses a string instead of a number as an index.
var normalArray = [];
normalArray[1] = 'This is an enumerated array';
alert(normalArray[1]); // outputs: This is an enumerated array
var associativeArray = [];
associativeArray['person'] = 'John Smith';
alert(associativeArray['person']); // outputs: John Smith
Javascript does not have, and does not support Associative Arrays. However… All arrays in Javascript are objects and Javascript's object syntax gives a basic emulation of an associative Array. For this reason the example code above will actually work. Be warned that this is not a real array and it has real pitfals if you try to use it. The 'person' element in the example becomes part of the Array object's properties and methods, just like .length, .sort(), .splice(), and all the other built-in properties and methods.
You can loop through an object's properties with the following loop…
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
for (i in associativeArray) {
document.writeln(i+':'+associativeArray[i]+', ');
// outputs: one:First, two:Second, three:Third
};
In the above example, associativeArray.length will be zero because we didn't actually put anything into the Array, we put it into associativeArray's object. associativeArray[0] will be undefined.
The loop in the above example will also pick up any methods, properties, and prototypes which have been added to the array and not just your data. A lot of problems people have with the Prototype library is that their associative arrays break because Prototype adds a few useful Prototype functions to the Array object and for i in x loops pick up those additional methods. That's the pitfal of using Array/objects as a poor man's associative array.
As a final example, the previous code will work regardless of whether you define associativeArray as an Array ([]), an Object({}), a Regular Expression (//), String(""), or any other Javascript object.
The bottom line is -- don't try to use associative arrays, code for what they are -- object properties, not Arrays.
Array Methods Reference
Since Javascript Arrays are modified objects, each and every Array you create has a few core methods. What's really interesting is that some of these methods implement basic data structures you'd normally have to write yourself such as stacks (push, pop) and queues (shift, unshift).
Method IE Version Mozilla Version Notes
concat 4.0 4.0 Joins multiple Arrays
every * FF 1.5 Calls a function for every element of the array until false is returned.
filter * FF 1.5 Creates an array with each element which evaluates true in the function provided.
forEach * FF 1.5 Executes a specified function on each element of an Array
join 3.0 3.0 Joins all the Array elements together into a string.
indexOf * FF 1.5 Searches the Array for specific elements.
lastIndexOf * FF 1.5 Returns the last item in the Array which matches the search critera.
map * FF 1.5 Creates a new array with the result of calling the specified function on each element of the Array.
pop 5.5 4.0 Returns the last item in the Array and removes it from the Array.
push 5.5 4.0 Adds the item to the end of the Array.
reverse 3.0 3.0 Reverses the Array so the last item becomes the first and vice-versa.
shift 5.5 4.0 Returns the first item in the Array and removes it from the Array.
slice 4.0 4.0 Returns a new array from the specified index and length.
some * FF 1.5 Passes each element through the supplied function until true is returned.
sort 3.0 3.0 Sorts the array alphabetically or by the supplied function.
splice 5.5 4.0 Deletes the specified index(es) from the Array.
toSource --- FF 1.5 Returns the source code of the array.
toString 3.0 3.0 Returns the Array as a string.
unshift 5.5 4.0 Inserts the item(s) to the beginning of the Array.
valueOf 3.0 3.0 Like toString, returns the Array as a string.
* Prototype functions are available to make this method available to Internet Explorer and older browsers.
Array.concat(value1[value2[value...]])
The concat method appends the passed values to the end of the Array, passing back a NEW array containing the joined values. The values passed to the concat method can be anything you can assign to a variable in Javascript.
var myArray = [1,2,3];
var newArray= [4,5,6];
var seven = 7;
var eight = 'eight';
var nine = {'sky':'blue', 'grass':'green'};
var joinedArray=myArray.concat(newArray, seven, eight, nine);
document.writeln(myArray); // outputs: 1,2,3
document.writeln(joinedArray); // outputs: 1,2,3,4,5,6,7,'eight',[object Object]
Supported Since: Netscape 4.0, IE 4.0
Array.every(function)
The every method is a Firefox method which accepts a function as an argument. Every value of the array is passed to that function until the function returns false. If no elements return false then every will return true, if an element returned false then every will return false. It's a convenient way to test an Array and see if every element is a number for instance.
This method will pass the current value, the current index, and a pointer to the array to your function. myfunction(curValue, curIndex, curArray)
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
document.writeln(myArray.every(isNumeric)); // outputs: true
var myArray = [1,2,3,4,5,6,7,8,9,'ten',11,12,13,14,15];
document.writeln(myArray.every(isNumeric)); // outputs: false
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .every() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.filter(function)
Filter creates a new Array of items which evaluate to true in the supplied function. In the Array.every() method, we tested if the entire Array was composed of Numbers. In Array.filter() we can extract all the numbers, creating a new Array in the process.
This method will pass the current value, the current index, and a pointer to the array to your function. myfunction(curValue, curIndex, curArray)
Here we pass the array through the same function as .every() -- isNumeric -- and if the element is a number it's placed in the new oddArray Array.
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var oddArray=myArray.filter(isNumeric);
document.writeln(oddArray); // outputs: 1,3,5,7,9
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .filter() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.forEach(function)
This is an odd little method. All it does is pass each element of the Array to the passed function. It ignores any results from the function and it returns nothing itself. It will pass all the Array contents through the function of your choice but the Array itself will not be affected and it will return nothing by itself.
This method will pass the current value, the current index, and a pointer to the array to your function. myfunction(curValue, curIndex, curArray)
var printArray = function (x, idx) {
document.writeln('['+idx+'] = '+x);
}
var myArray = [1,'two',3,'four',5];
myArray.forEach(printArray); // outputs: [0] = 1 [1] = two [2] = 3 [3] = four [4] = 5
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .forEach() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.join(delimeter)
The join method will output your Array as a string with a delimiter of your choice. This is a very useful function if you need to convert an Array into something you can send back to the server. Simply pick a unique delimiter which is not likely to appear inside the data in your Array then you can turn it back into an Array on the server side.
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var test1 = myArray.join();
var test2 = myArray.join(', ');
var test3 = myArray.join('+');
document.writeln(test1+'
'); // outputs: 1,two,3,four,5,six,7,eight,9,ten
document.writeln(test2+'
'); // outputs: 1, two, 3, four, 5, six, 7, eight, 9, ten
document.writeln(test3+'
'); // outputs: 1+two+3+four+5+six+7+eight+9+ten
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.indexOf(searchStr[, startIndex])
The indexOf method will search the array until it matches your search critera. It will then return the index where the item was found. It will match only one item and the match must be exact. This is not as useful as the custom .find() method provided below in the Useful Prototypes section.
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
document.writeln(myArray.indexOf('six')); // outputs: 5
document.writeln(myArray.indexOf('not here')); // outputs: -1
To find and return all occurrences of an item you can use the following code…
var foundItems = [];
var index = array.indexOf(element)
while (index != -1)
{
foundItems.push(index);
index = array.indexOf(element, ++index);
}
This will create an array of indexes which match your search criteria (element) and store them in foundItems[].
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .indexOf() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.lastIndexOf(searchStr[, startIndex])
Array.indexOf() searches from first to last, lastIndexOf searches from last to first.
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,5,'ten'];
document.writeln(myArray.lastIndexOf(5)); // outputs: 9
document.writeln(myArray.lastIndexOf('not here')); // outputs: -1
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .lastIndexOf() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]);
if (isNaN(from))
{
from = len - 1;
}
else
{
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
else if (from >= len)
from = len - 1;
}
for (; from > -1; from--)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.map(function)
The map method will call the provided function for each value of the array and it will return an array containing the results of those function calls.
The callback function is called with three arguments: the value, the index, and a pointer to the array being used respectively.
In the following example each element of the array is tested to see if it is numeric, if it is, it's passed into the new array, otherwise a zero is inserted.
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var testElement = function(x) {
if (isNumeric(x)) {
return x;
} else {
return 0;
}
}
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var newArray= myArray.map(testElement);
document.writeln(newArray); // outputs: 1,0,3,0,5,0,7,0,9,0
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .map() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.pop()
The pop() method implements a basic stack structure in Javascript Arrays. Array.pop() will return the last element of an Array and delete it from the Array.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
document.writeln(myArray.length+'
'); // outputs: 10
var popped = myArray.pop();
document.writeln(popped+'
'); // outputs: 10
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9
document.writeln(myArray.length+'
'); // outputs: 9
Supported Since: Netscape 4.0, Internet Explorer: 5.5
Array.push(value[,value2[, value...]])
The push() method adds the passed value(s) to the end of the array. In addition to being incredibly useful for adding items to the array, it also allows the Array to emulate a basic stack structure.
var myArray = [1,2,3,4,5];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5
document.writeln(myArray.length+'
'); // outputs: 5
myArray.push(6);
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6
document.writeln(myArray.length+'
'); // outputs: 6
myArray.push(7,8,9,10);
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
document.writeln(myArray.length+'
'); // outputs: 10
Supported Since: Netscape 4.0, Internet Explorer: 5.5
Array.reverse()
The reverse() method takes the array and reverses the order so the first item becomes the last and the last item becomes the first.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
myArray.reverse();
document.writeln(myArray+'
'); // outputs: 10,9,8,7,6,5,4,3,2,1
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.shift()
The shift() method returns the first item in the Array, removing it from the Array in the process. Together with Array.unshift, Shift implements a basic queue structure in Javascript Arrays.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
theItem = myArray.shift();
document.writeln(theItem+'
'); // outputs: 1
document.writeln(myArray+'
'); // outputs: 2,3,4,5,6,7,8,9,10
Supported Since: Netscape 5.5, Internet Explorer: 4.0
Array.slice([begin[, end]])
The slice() method copies a block of the array and returns it to your new variable. If you don't specify a beginning index the slice will begin at zero. If you don't specify and ending index the splice will continue to the end of the Array. So to make a copy of the array simply don't pass any arguments to the method.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
var newArray = myArray.slice();
document.writeln(newArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
var newArray = myArray.slice(5);
document.writeln(newArray+'
'); // outputs: 6,7,8,9,10
var newArray = myArray.slice(5,7);
document.writeln(newArray+'
'); // outputs: 6,7
Supported Since: Netscape 4.0, Internet Explorer: 4.0
Array.some(function)
The some() method will pass each element of the Array through the supplied function until true has been returned. If the function returns true some will in turn return true. If the entire array has been traversed and no true condition was found then some() will return false.
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var myArray = ['one', 'two', 'three', 'four', 'five'];
document.writeln(myArray.some(isNumeric)); // outputs: false
var myArray = ['one', 'two', 3, 'four', 'five'];
document.writeln(myArray.some(isNumeric)); // outputs: true
This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .some() method will be available regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
fun.call(thisp, this[i], i, this))
return true;
}
return false;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.sort([function])
The sort() method, by default, will sort an Array alphabetically. If you would like to create your own sorting criteria, supply a function for the sort method to call. Sort will pass your function (a,b). If a is less than b then return -1, if a is equal to b then return 0, if a is greater than b then return 1. Sort will take it from there.
var myArray=[8,10,50,5,7,83,24,19,168];
myArray.sort()
document.writeln(myArray); // 10,168,19,24,5,50,7,8,83 (sorted alphabetically)
myArray.sort( function (a,b) { return a-b }); // Sort Numerically
document.writeln(myArray); //5,7,8,10,19,24,50,83,168
function compare(a, b) {
// psudeo code.
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
if (a == b) {
return 0;
}
}
myArray.sort(compare);
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.splice(start[, howmany[, element1[,element...]]])
The splice() method at it's most basic allows you to delete an element from the array by simply specifying the index you'd like to delete and then how many elements you'd like to delete from that point. You can also specify any number of elements to insert into the array at that point.
splice() returns a new array containing the removed items. If you specify a starting number but don't specify how many, splice will truncate the array.
You can insert elements into the array without deleting anything by specifying zero for howmany.
var myArray=[1,2,3,4,5,6,7,8,9,10];
var newArray=[];
//delete one item at the 5th index.
newArray = myArray.splice(5,1);
document.writeln(myArray); // outputs: 1,2,3,4,5,7,8,9,10
document.writeln(newArray); // outputs 6
//truncate the array at the 5th index.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(5);
document.writeln(myArray); // outputs: 1,2,3,4,5
document.writeln(newArray); // outputs 6,7,8,9,10
// do nothing at all.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice();
document.writeln(myArray); // outputs: 1,2,3,4,5,6,7,8,9,10
document.writeln(newArray); // outputs undefined
// cut out the middle and insert 'blue', and 'green'
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(1,8, 'blue', 'green');
document.writeln(myArray); // outputs: 1,blue,green,10
document.writeln(newArray); // outputs 2,3,4,5,6,7,8,9
// Insert without deleting.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(5,0, '*');
newArray = myArray.splice(4,0, '*');
document.writeln(myArray); // outputs: 1,2,3,4,*,5,*,6,7,8,9,10
Supported Since: Netscape 4.0, Internet Explorer: 5.5
Array.toSource()
The toSource() method is a Firefox only extension which takes the contents of an Array and returns the source code. That is, if you were to use the toSource() method and pass it through an eval statement you could rebuild the array. This is a useful debugging method and can be useful in Ajax/JSON applications. There is no prototype for this method, it works only in Firefox.
var myArray = ["a", "b", "c", {'sky':'blue', 'grass':'green'}];
var theSource = myArray.toSource()
document.writeln(theSource); // outputs: ["a", "b", "c", {sky:"blue", grass:"green"}]
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.toString()
This method outputs the contents of the Array as a string. It's not as powerful as toSource() since it doesn't expand objects but it is supported by browsers other than firefox.
var myArray = ["a", "b", "c", {'sky':'blue', 'grass':'green'}];
var theSource = myArray.toString()
document.writeln(theSource); // outputs: a,b,c,[object Object]
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.unshift(value1[, value2[, value...]])
The unshift method inserts the value(s) passed in the method's arguments into the start of the Array. Together with the shift(), unshift() implements a basic queue structure in Javascript Arrays.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'
'); // outputs: 1,2,3,4,5,6,7,8,9,10
myArray.unshift('a','b','c');
document.writeln(myArray+'
'); // outputs: a,b,c,1,2,3,4,5,6,7,8,9,10
Supported Since: Netscape 5.5, Internet Explorer: 4.0
Array.valueOf()
See Array.toString().
Howto Delete An Element From An Array
You can delete an item from an Array with the splice() method. Simply supply the index of the item you wish to delete and how many items you want to delete and the item(s) will be removed for you.
var myArray=[1,2,3,4,5,6,7,8,9,10];
myArray.splice(5,1); //delete one item at the 5th index.
document.writeln(myArray); // outputs: 1,2,3,4,5,7,8,9,10
Howto Easily Add Items To An Array
There are three ways to easily add items to an array. First you can use the Array.length property. Since Arrays start with index 0, then Array.length is always equal to the first empty index at the end of the Array.
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
document.writeln(myArray.length); // Will output: 2
myArray[myArray.length] = 'March'; // Adds Item to end of Array
document.writeln(myArray.length); // Will output: 3
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>March
You can add the .push() method of the Array. This will add the requested items to the end of the Array.
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray.push('March'); // Adds Item to end of Array
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>March
You can use the .unshift() method to insert an item at the BEGINNING of the array!
var myArray = [];
myArray[0] = 'February';
myArray[1] = 'March';
myArray.unshift('January'); // Adds Item to beginning of Array
document.writeln('0>'+myArray[0]+'
'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'
'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'
'); // Will output: 2>March
Howto Clear-out/Reset An Array
Clearing out or resetting an array is as simple as assigning it a new empty bracket.
var myArray=[1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray); // outputs: 1,2,3,4,5,6,7,8,9,10
myArray = []; // clear-out the array
document.writeln(myArray); // outputs null
Alternatively you can set the length of the array to zero (myArray.length=0), likewise if you just need to clear out a few items at the end of the array, lower the length property by the number of items you would like removed from the end of the array.
Howto Tell The Difference Between An Array And An Object
Because Javascript's Array is just a modified Javascript object, it's actually not that easy to differentiate an Array and an Object, even when you absolutely need to. So here's a little function that will let you ask the array itself what it is. isArray() will return true if it's an array and false if it is not an Array.
function isArray(testObject) {
return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}
Usage…
var tmp = [5,9,12,18,'blue',30,7,97,53,33,30,35,27,30];
var tmp2 = {0:5,1:9,2:12}
test1 = isArray(tmp); // returns true
test2 = isArray(tmp2); // returns false;
Howto Pass An Array Via Ajax
If you have an Array you need to package up and send via Ajax, you need to use the join method to turn your Array into a string. Find a unique character that is unlikely to appear inside your Array and use it as your delimiter. For most applications the tildie (~) character is a safe delimeter to use.
var myArray=[1,2,3,4,5,6,7,8,9,10];
var theData = myArray.join('~'); // theData=1~2~3~4~5~6~7~8~9~10
theData=encodeURIComponent(theData); // Optional but safe! Escape the data
Now just send theData through your ajax routine. On the server just do a split('~') in php to turn it back into an Array.
Howto Receive An Array Via Ajax
On the server side convert the Array into a string using a unique delimiter -- implode in php. (We're assuming a string with a tildie [~] delimiter in this example).
Once you've received the string from your Ajax handler simply use the string's split method to bust the string into an Array.
var ajaxStr = '1~2~3~4~5~6~7~8~9~10';
var myArray = ajaxStr.split('~');
document.writeln(myArray); // outputs: 1,2,3,4,5,6,7,8,9,10
Useful Prototypes
With prototypes you can extend the Array object and include any additional functionality you wish. For instance, the Array.sort() method sorts alphabetically by default but adding a numerical sort is as simple as including the following snippet of code in your toolbox.
Array.prototype.sortNum = function() {
return this.sort( function (a,b) { return a-b; } );
}
All this does is make sortNum a method of Array just like sort and splice and join and all the other default methods. Any array can access it, even arrays that haven't been assigned to variables…
document.writeln([5,8,12,50,25,80,93].sortNum()); // outputs 5,8,12,25,50,80,93
Since the Javascript Array object is already so rich, there's not much left that needs to be done. However, there are a few snippets people have found helpful.
Useful Prototypes: Array.sortNum()
As stated above, just use the sortNum() method when you want to sort an array numerically instead of alphabetically.
Array.prototype.sortNum = function() {
return this.sort( function (a,b) { return a-b; } );
}
Useful Prototypes: Array.find(searchStr)
Array.indexOf() is a nice method but this extension is a little more powerful and flexible. First it will return an array of all the indexes it found (it will return false if it doesn't find anything). Second in addition to passing the usual string or number to look for you can actually pass a regular expression, which makes this the ultimate Array prototype in my book.
Array.prototype.find = function(searchStr) {
var returnArray = false;
for (i=0; i
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
if (this[i]===searchStr) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}
Usage…
var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble'];
// 0/1/2 /3 /4/5 /6 /7 /8 /9/10/11/12/13/14/15/16/17/ 18/ 19/ 20
var thirty=tmp.find(30); // Returns 9, 14, 17
var thirtyfive=tmp.find('35'); // Returns 18
var thirtyfive=tmp.find(35); // Returns 15
var haveBlue=tmp.find('blue'); // Returns 8
var notFound=tmp.find('not there!'); // Returns false
var regexp1=tmp.find(/^b/); // returns 8,20 (first letter starts with b)
var regexp1=tmp.find(/^b/i); // returns 8,19,20 (same as above but ignore case)
Useful Prototypes: Array.shuffle()
The anti-sort, this shuffle() method will take the contents of the array and randomize them. This method is surprisingly useful and not just for shuffling an array of virtual cards.
Array.prototype.shuffle = function (){
for(var rnd, tmp, i=this.length; i; rnd=parseInt(Math.random()*i), tmp=this[--i], this[i]=this[rnd], this[rnd]=tmp);
};
Usage…
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
myArray.shuffle();
document.writeln(myArray); // outputs~: 8,1,13,11,2,3,4,12,6,14,5,7,10,15,9
Useful Prototypes: Array.compare(array)
If you need to be able to compare Arrays this is the prototype to do it. Pass an Array you want to compare and if they are identical the method will return true. If there's a difference it will return false. The match must be identical so '80' is not the same as 80.
Array.prototype.compare = function(testArr) {
if (this.length != testArr.length) return false;
for (var i = 0; i < testArr.length; i++) {
if (this[i].compare) {
if (!this[i].compare(testArr[i])) return false;
}
if (this[i] !== testArr[i]) return false;
}
return true;
}
Usage…
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var yourArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
document.writeln(myArray.compare(yourArray)); // outputs: true;
yourArray[0]='1';
document.writeln(myArray.compare(yourArray)); // outputs: false;
yourArray[0]='one';
document.writeln(myArray.compare(yourArray)); // outputs: false;
yourArray[0]=1;
document.writeln(myArray.compare(yourArray)); // outputs: true;
Ref: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Subscribe to:
Posts (Atom)
