Студопедия

КАТЕГОРИИ:

АвтоАвтоматизацияАрхитектураАстрономияАудитБиологияБухгалтерияВоенное делоГенетикаГеографияГеологияГосударствоДомЖурналистика и СМИИзобретательствоИностранные языкиИнформатикаИскусствоИсторияКомпьютерыКулинарияКультураЛексикологияЛитератураЛогикаМаркетингМатематикаМашиностроениеМедицинаМенеджментМеталлы и СваркаМеханикаМузыкаНаселениеОбразованиеОхрана безопасности жизниОхрана ТрудаПедагогикаПолитикаПравоПриборостроениеПрограммированиеПроизводствоПромышленностьПсихологияРадиоРегилияСвязьСоциологияСпортСтандартизацияСтроительствоТехнологииТорговляТуризмФизикаФизиологияФилософияФинансыХимияХозяйствоЦеннообразованиеЧерчениеЭкологияЭконометрикаЭкономикаЭлектроникаЮриспунденкция

JavaScript History Object, Working with JavaScript Objects and Arrays (JavaScript)




The History object is a predefined object in JavaScript that consists of an array of URLs, which are visited by a user in the browser.

The history object has the following features:

· properties

· methods

JavaScript History Object Properties.The following table lists the properties of the history object in JavaScript.

Property Description
Length specifies the number of elements contained in the object
Current specifies the URL of the current entry in the object
Next specifies the URL of the next element in the History list
previous specifies the URL of the previous element in the History list

JavaScript History Object Methods.The table given below describes the methods of the history object in JavaScript.

 

Methods Description
back() specifies a method that loads the previous URL from the history list
forward() specifies a method that loads the next URL from the history list
go() specifies a method that loads a specific URL from the history list

Working with JavaScript Objects.Before you can write an object variable, you should understand the premise of an object. An object defines a set of properties related to a specific part of your application. For instance, if you have an ecommerce site, you have different parts of your site related to the store. You have customers, orders, products, and information related to these objects. Let's take a customer, for instance. A customer has an address, phone number, first name and last name. The amount of properties for a customer is up to you and how you design your application. But, let's start with creating a customer object with some standard properties.

     

var customer = {

first_name: 'Joe',

last_name: 'Smith',

phone: '999-999-9999'};

We've seen the "var" keyword before. This keyword tells JavaScript that we're creating a variable. In this example, we've created a custom object named "customer." We've then created properties named "first_name," "last_name," and "phone." After the colon, we've defined values for these properties.

What if you don't have data that you want to use for an object? No problem. JavaScript lets you create standard objects without defining any custom data on-the-fly. The following code also creates a customer object, but the data isn't filled until after the object is created.

var customer = new Object();

customer.first_name = 'Joe';

customer.last_name = 'Smith';

customer.phone = '999-999-9999';

Notice that this code instantiates the internal "Object()" object. This is the base object to create custom objects within your code. This object gives you the ability to instantiate an object without giving it any data. Both methods work for your JavaScript code, and you can instantiate an object as many times as you need to fill a database with information. You can also return data to the web page and print it on the user's browser. This will involve using a new method we haven't seen yet.

The "document" object contains a number of methods that help you interact with a web page's HTML. We'll discuss JavaScript with HTML in later chapters, but the "document.write()" method is convenient when you want to test your JavaScript code. Let's take the previous customer object and print it on the web page.

document.write(customer.first_name);

document.write("<br/>");

document.write(customer.last_name);

The above statement writes the customer's first and last name to the web page. This snippet of code is used to give you an example of how you can return data you stored in an object's properties. If you notice, the code that prints the text on the web page is similar to the customer object. That's because the document object is native to the JavaScript language. This object contains several properties and methods that you'll use to interact with a web page's document object model (DOM). We'll discuss the DOM in later lessons.

The Array Object.If you've performed any kind of programming before, you might be familiar with arrays. In JavaScript, an array is another object you use to hold values. Instead of assigning and calling properties, an array lets you call values using an index. An index describes the location of a value stored in memory. With an array object, you defined the number of values you want to store, and retrieve these values based on their associated index. It's important to remember that arrays start at the index 0. The index 0 is the first element of an array, the index 1 is the second element, index 2 is the third value, and so on.

Let's start off with defining an array. The following code defines an array that will hold three values.

var customer = new Array(3);

 

 

Notice that the number 3 in the array parenthesis indicates the number of values that the array can hold. However, again the values start with an index of 0. This concept is important to remember when assigning and retrieving values. You can also assign values to an array in the same way you assign them immediately in an object. The following code also creates a "customer" array but also assigns data to each array index.

var customer = [

'Joe',

'Smith',

'999-999-9999'];

Again, the above code holds three values. The first name is assigned the index of 0, last name is assigned index 1, and the phone number is given index 2.

Let's go back to the first array code. We've assigned a variable named "customer" to the "Array" object that allows for three values. Now, let's assign values based on index number. Look at the following code.

var customer = new Array(3);

customer[0] = 'Joe';

customer[1] = 'Smith';

customer[2] = '999-999-9999';

Notice that instead of assigning values on-the-fly, we've assigned values based on the index numbers. These index number serve not only the purpose of assigning values, but also a looping purpose. You can use loop structures to streamline your coding process and iterate through each array value based on its index. Let's take the following code as an example.

for (int j = 0; j < 3; j++)

{document.write(customer[j]);}

We discussed for loops in the previous chapter. For loops tie in with arrays in most programming languages. Notice that instead of calling an index by number, we use the j variable. The j variable is initialized with the value 0 in your opening for loop structure, so the first loop returns the value held in the customer array's index 0. The loop returns and j is incremented by 1. Now, j has a value of 1, so the JavaScript code prints out the value held in the array's 1 index or the second value, which is the customer's last name. Finally, the loop returns again, j is incremented again, and now j has a value of 2. The value (phone number) is printed to the web page. Now that j is incremented to 3, it is no longer less than three, which is the condition that must be met for the for loop to continue. The for loop exits and you've iterated through all values of your array. This type of loop and its logic is widely used across JavaScript and other programming languages, so it's a good idea to practice with this type of coding when you're a beginner.

Multidimensional arrays are also a big part of programming. You can think of multidimensional arrays as a matrix. For each row, there are a number of columns. Let's use the multiplication table as an example. Let's keep it simple and just use three rows and three columns. With this matrix, we have 9 values. You'll use multidimensional arrays with embedded for loops. Take a look at the following code example.

var row = new Array(3);

for (int j = 0; j < 3; j++)

{row[j] = new Array(3);

for (int k = 0; k < 3; k++)

{ row[j][k] = j * k;}}

The above code is more complex than the previous example. The first line of code defines the number of rows for the multiplication table. Remember, the number 3 defines the number of values but the index numbers are 0 to 2.

The for loop creates a new array for each row. This new array is used for the columns in our multiplication matrix. The embedded loop with the k variable loops through each column and assigns a value to the row's columns. The main outer loop continues for 2 more runs and creates a multiplication table.

Arrays and objects are common in most JavaScript apps. When you work with libraries such as AngularJs or KnockoutJs, you'll use objects extensively. Objects also allow you to customize your JavaScript structures as you define them on your web pages. Use objects to represent the properties and information on your pages, so they are more easily readable when you need to document or edit your code.

Advanced Javascript: Objects, Arrays, and Array-Like objects

Javascript objects and arrays are both incredibly useful. They're also incredibly easy to confuse with each other. Mix in a few objects that look like arrays and you’ve got a recipe for confusion!

We're going to see what the differences between objects and arrays are, how to work with some of the common array-like objects, and how to get the most performance out of each.

What Objects Are? A javascript object is a basic data structure:

varbasicObj = {}; // an empty object - {} is a shortcut for "new Object()"

basicObj.suprise= "cake!";

basicObj['suprise']; // returns "cake!"

Using {} instead of new Object(); is know as “Object Literal” syntax.

varfancyObj = {

favoriteFood: "pizza",

add: function(a, b){

return a + b;}};

fancyObj.add(2,3); // returns 5

fancyObj['add'](2,3); // ditto.

As you can see, and probably already knew, properties can be accessed a couple of different ways. However, it’s an important point that we’ll come back to in a minute.

Everything in javascript is an object. Everything. Arrays, functions, even numbers! Because of this, you can do some really interesting things, such as modifying the prototypes of Objects, Arrays, etc.

// an example of something you probably shouldn't do. Ever.Seriously.

Number.prototype.addto = function(x){

return this + x;}

(8).addto(9); // returns 17

// other variations:

8.addto(9); // gives a syntax error, because the dot is assumed to be a decimal point

8['addto'](9); // works but is kind of ugly compared to the first method

var eight = 8;

eight.addto(9); // works

What Arrays Are? Javascript arrays are a type of object used for storing multiple values in a single variable. Each value gets numeric index and may be any data type.

vararr = []; // this is a shortcut for new Array();

arr[0] = "cat";

arr[1] = "mouse";

See how that syntax is so similar to the syntax used for setting object properties? In fact, the only difference is that objects use a string while arrays use a number. This is why arrays get confused with objects so often.

Length.Arrays have a length property that tells how many items are in the array and is automatically updated when you add or remove items to the array.

vararr = [];

arr[0] = "cat"; // this adds to the array

arr[1] = "mouse"; // this adds to the array

arr.length; // returns 2

arr["favoriteFood"] = "pizza"; // this DOES NOT add to the array. Setting a string parameter adds to the underlying object

arr.length; // returns 2, not 3

The length property is only modified when you add an item to the array, not the underlying object.The length is always 1 higher than the highest index, even if there are actually fewer items in the array.

vararr = [];

arr.length; // returns 0;

arr[100] = "this is the only item in the array";

arr.length; // returns 101, even though there is only 1 object in the array

This is somewhat counter-intuitive. PHP does more what you would expect:

<?php

arr = array();

arr[100] = "php behaves differently";

sizeof(arr); // returns 1 in PHP

?>

You can manually set the length also. Setting it to 0 is a simple way to empty an array.In addition to this length property, arrays have lots of nifty built in functions such as push(), pop(), sort(), slice(), splice(), and more. This is what sets them apart from Array-Like Objects.

Array-like Objects.Array-like objects look like arrays. They have various numbered elements and a length property. But that’s where the similarity stops. Array-like objects do not have any of Array’s functions, and for-in loops don’t even work!

You’ll come across these more often than you might expect. A common one is the arguments variable that is present inside of every js function.

Also included in the category are the HTML node sets returned by document.getElementsByTagName(), document.forms, and basically every other DOM method and property that gives a list of items.

document.forms.length; // returns 1;

document.forms[0]; // returns a form element.

document.forms.join(", "); // throws a type error. this is not an array.

typeofdocument.forms; // returns "object"

Did you know you can send any number of arguments you want to a javascript function? They're all stored in an array-like object named arguments.

functiontakesTwoParams(a, b){

// arguments is an array-like variable that is automatically created

// arguments.length works great

alert ("you gave me "+arguments.length+" arguments");

for(i=0; i&lt; arguments.length; i++){

alert("parameter " + i + " = " + arguments[i]);}}

takesTwoParams("one","two","three");

// alerts "you gave me 3 arguments",

// then "parameter 0 = one"

// etc.

Tip: Parameters are the named variables in a function's signature: a and b in the previous example.

Arguments, by contrast, are the expressions that are used when calling the function: "one", "two", and "three" in this case.

This works great. But that's about as far as you can go with array-like objects. The flowing example does not work:

functiontakesTwoParams(a, b){

alert(" your parameters were " + arguments.join(", "));

// throws a type error because arguments.join doesn't exist}

So what can you do?Well you could make your own join() function, but that adds a lot of unnecessary overhead to your code because it has to loop over everything. If only there were a quick way to get an array out of an array like object…

It turns out there is.The array functions can be called on non-array objects as long as you know where to find the function (usually they’re attached to the array, but this isn’t an array remember

Prototype to the win:

functiontakesTwoParams(a, b){

varargs = Array.prototype.slice.call(arguments);

alert(" your parameters were " + args.join(", "));

// yay, this works!}

Let’s take a look at that a bit more in-depth:

Array: This object is the original array that all other arrays inherit their properties from.

Array.prototype:This gives us access to all the methods properties that each array inherits

Array.prototype.slice: The original slice method that is given to all arrays via the prototype chain. We can’t call it directly though, because when it runs internally, it looks at the this keyword, and calling it here would make this point to Array, not our arguments variable.

Array.prototype.slice.call(): call() and apply() are prototype methods of the Function object, meaning that they can be called on every function in javascript. These allow you to change what the this variable points to inside a given function.

And finally, you get a regular array back! This works because javascript returns a new object of type Array rather than whatever you gave it. This causes a lot of headaches for a few people who are trying to make subclasses of Array, but it’s very handy in our case!Gotchas

First, in Internet Explorer, DOM NodeLists are not considered to be javascript objects, so you cannot call Array.prototype.slice on them. If you want an array, you’ll have to loop through it the old fashioned way. Or use a hybrid function that tries it the fast way first, then the slow way if that doesn’t work.

functionhybridToArray(nodes){

try{

// works in every browser except IE

vararr = Array.prototype.slice.call(nodes);

returnarr;

} catch(err){

// slower, but works in IE

vararr = [],

length = nodes.length;

for(var i=0; i &lt; length; i++){

arr.push(nodes[i]);}

returnarr;}}

See an example here: http://nfriedly.com/demos/ie-nodelist-to-array.Second, arrays are objects, so you can do this, but it can get you some serious inconsistencies:

arr = [];

arr[0] = "first element"; // adds item to the array

arr.length; // returns 1

arr.two = "second element"; // adds an item to the underlying object that array is built on top of.

arr.length; // still returns 1 !

// BUT...

for(i in arr){

// this will hit both 0 and "two"}

Another solution: wrap arrays in an object if you need both worlds. This is basically a less efficient method of the array subclassing links I mentioned above. While less efficient, it has the advantage of being simple and reliable.That said, I wouldn’t recommend that you use this in most cases due to issues with speed and extra code requirements. It’s provided here as an example.

// an example of a wrapper for an array.

// not recommended for most situations.

varArrayContainer = function(arr){

this.arr = arr || [];

this.length = this.arr.length;};

ArrayContainer.prototype.add= function(item){

index = this.arr.length;

this.arr[index] = item;

this.length = this.arr.length;

return index;};

ArrayContainer.prototype.get= function(index){

returnthis.arr[index];};

ArrayContainer.prototype.forEach= function(fn){

if (this.arr.forEach) this.arr.forEach(fn);// use native code if it's there

else {

for(i in this.arr){

fn( i, this.arr[i], this.arr );}}};

varmySuperDooperArray = new ArrayContainer();

Now that your array is (somewhat) protected on the inside, you can loop through it’s items with forEach() and know that they will match it’s length. You can also add arbitrary properties to ArrayContainer or mySuperDooperArray and they won’t get pulled into your forEach() loop.

This example could be extended to completely protect the array if the need arose.

Objects and Arrays (JavaScript). JavaScript objects are collections of properties and methods. A method is a function that is a member of an object. A property is a value or set of values (in the form of an array or object) that is a member of an object. JavaScriptsupportsfourkindsofobjects:

· Intrinsic objects, such as Array and String.

· Objectsyoucreate.

· Host objects, such as window and document.

· ActiveXobjects.

Expando Properties and Methods.All objects in JavaScript support expando properties and methods, which can be added and removed at run time. These properties and methods can have any name and can be identified by numbers. If the name of the property or method is a simple identifier, it can be written after the object name with a period, such as myObj.name, myObj.age, and myObj.getAge in the following code:

varmyObj = newObject(); 

myObj.name = "Fred"; 

myObj.age = 42; 

myObj.getAge =  

function () {

returnthis.age; }; 

document.write(myObj.name); 

document.write("<br/>"); 

document.write(myObj.age); 

document.write("<br/>");

document.write(myObj.getAge()); 

// Output: 

// Fred 

// 42 

// 42 

If the name of the property or method is not a simple identifier or is unknown at the time you write the script, you can use an expression inside square brackets to index the property. The names of all expando properties in JavaScript are converted to strings before being added to the object.

varmyObj = newObject(); 

// Add two expando properties that cannot be written in the 

// object.property syntax. 

// The first contains invalid characters (spaces), so must be 

// written inside square brackets. 

myObj["not a valid identifier"] = "This is the property value"; 

// The second expando name is a number, so it also must 

// be placed inside square brackets 

myObj[100] = "100"; 

For information about creating an object from a definition, see Creating Objects.

Arrays as Objects.In JavaScript, objects and arrays are handled almost identically, because arrays are merely a special kind of object. Both objects and arrays can have properties and methods.

Arrays have a length property but objects do not. When you assign a value to an element of an array whose index is greater than its length (for example, myArray[100] = "hello"), the lengthproperty is automatically increased to the new length. Similarly, if you make the length property smaller, any element whose index is outside the length of the array is deleted.

// An array with three elements 

varmyArray = newArray(3); 

// Add some data 

myArray[0] = "Hello"; 

myArray[1] = 42; 

myArray[2] = newDate(2000, 1, 1);

document.write("original length is: " + myArray.length); 

document.write("<br/>"); 

// Add some expando properties 

myArray.expando = "JavaScript!";

myArray["another Expando"] = "Windows";

// This will still display 3, since the two expando properties 

// don't affect the length. 

document.write("new length is : " + myArray.length);

// Output: 

// original length is: 3 

// new length is : 3 

Arrays provide methods to iterate over and manipulate members. The following example shows how to obtain the properties of objects stored in an array.

varmyArray = newArray(3); 

// Add some data 

for(var i = 1; i <= 3; i++) { 

myArray[i] = newDate(2000 + i, 1, 1); }

myArray.forEach(function (item) { 

document.write(item.getFullYear()); });

// Output: 

// 2001 

// 2002 

// 2003 

Multi-Dimensional Arrays.JavaScript does not directly support multi-dimensional arrays, but you can get the behavior of multi-dimensional arrays by storing arrays within the elements of another array. (You can store any sort of data inside array elements, including other arrays.) For example, the following code builds a multiplication table for the numbers up to 5.

// The size of the table. 

variMaxNum = 5; 

// Loop counters. 

var i, j;

// Set the length of the array to iMaxNum + 1.  

// The first array index is zero, not 1. 

varMultiplicationTable = newArray(iMaxNum + 1);

// Loop for each major number (each row in the table) 

for (i = 1; i <= iMaxNum; i++) 

// Create the columns in the table 

MultiplicationTable[i] = newArray(iMaxNum + 1);

// Fill the row with the results of the multiplication 

for (j = 1; j <= iMaxNum; j++) 

MultiplicationTable[i][j] = i * j; } } 

document.write(MultiplicationTable[3][4]); 

document.write("<br/>");  

document.write(MultiplicationTable[5][2]); 

document.write("<br/>"); 

document.write(MultiplicationTable[1][4]);

// Output: 

// 12 

// 10 

// 4 

Arrays.An array is a set of elements, which are accessed by index. An array is created using the new operator and the array constructor - function Array. Suppose you want to create an array of user names. Thiscanbedoneasfollows:

var users = new Array("Artem", "Irina", "Sergey", "Boris");

This statement creates an array of 4 elements (users). All the elements of the array are numbered starting from zero. To get the value of the array element you need to specify the name of the array and in square brackets the atomic number (the index). So, to gain access to the first element of our array, you could write:

users[0]

The values of the array does not necessarily give at once. For example, it is possible to take advantage of such construction:

varusers = newArray(4);

This expression also creates an array of four elements, but the values of the elements can be specified later by using the assignment operator:

users[0] = "Artem"; users[1] = "Irina"; users[2] = "Sergey"; users[3] = "Boris";

And finally, you can use the constructor without parameters:

varusers = newArray();

In this case, we specify that created variable users will be the array, whose size will be determined automatically as the elements come. To determine the length of the array (ie, the number of elements in it) the property length is used. For example, access to the last element of the array (if we do not know how many elements in it) as follows:

users[users.length-1];

I.e. first determined the length of the array (users.length), then, mindful of the fact that the numbering of the elements begins with zero, 1 is subtracted from the length; and the resulting value is used as an array index. Here's an example: suppose we want when the page is loaded the user could to see which day of the week today. Code html-pages is as follows:

<html>

<head>

<title>javascriptмассивы</title>

<link rel="stylesheet" type="text/css" href="style.css">

<script type="text/javascript" src="script.js"></script>

</head>

<body onload="showDay();">

</body>

</html>

 

* Earlier we have considered the events and their handlers. In this case, we will use the event Load (document is loaded in the browser) and its handler - onload. In other words, our function showDay () should be triggered when the document loads. *

Now let’s write the function showDay():

Function showDay() {

varnDays=newArray("воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота");

var now=new Date();

var day=now.getDay();

variDay=nDays[day];

varstr="Сегодня - " + iDay;

document.write(str);}

 

Let’s consider in detail.First, we create an array nDays of seven elements (in the previous lesson, we talked about that zero corresponds to “воскресенье”):

VarnDays=newArray("воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота");

Then, from the current date we get the current day of the week (its numeric equivalent):

var now=new Date();

var day=now.getDay();

and we use it as an index to access the element in the array:

variDay=nDays[day];

The last two lines form and reflect the result of:

Varstr="Сегодня- " + iDay;

document.write(str);

Try toworkthe scriptin actionand make sure thatwhen the page loads, there is a phrase such as"Today-Friday".Let’s continue. The two arrays can be combined into one using the method concat (). Suppose we have two massiva A and B, and we want them to be combined into one - c :

var a=new Array(1, 2, 3);

var b=new Array(4, 5, 6);

var c=a.concat(b);  

At the output we obtain an array C of six elements 1, 2, 3, 4, 5, 6.

The arrays can be sorted using the method sort(), is true only in the lexicographical order (ie, as a string).

For example, if you apply the sort() method to the array with the names:

var users = new Array("Artem", "Irina", "Sergey", "Boris");

var c=users.sort();

at the output we obtain an array C: Artem, Boris, Irina, Sergey.And if you apply the sort() method to the array with the numbers:

var n = new Array(11, 12, 10, 107, 3, 20, 25, 101, 14, 34, 44, 5, 4);

var c=n.sort();

then at the output we obtain the following array: 10, 101, 107, 11, 12, 14, 20, 25, 3, 34, 4, 44, 5.

I.e. elements are compared as string and not as a number. So apply the sort () method should be cautious. We now consider an example of how to search for a specific item in the array. Suppose we have an array of 6 names, and we want to know whether there is in it a certain name.

Code html-pages is simple:

 

<html>

<head>

<title>javascript Arrays</title>

<link rel="stylesheet" type="text/css" href="style.css">

<script type="text/javascript" src="script.js"></script>

</head>

<body>

<form name="forma10">

Enter a namefor thetest:

<input type="text" size="20" name="name">

<input type="button" value="Проверить" onClick="proverka(forma10);">

</form>

</body>

</html>

 

Let’s write the function proverka() on the page script.js:

Function proverka(obj) {

var k;

var users = new Array("Artem", "Irina", "Sergey", "Boris", "Olga", "Viktor");

var n=obj.name.value;

for (var i=0; i<=users.length-1; i++){

if (users[i]==n)

{k=0; break}}

if (k==0){alert("This name is in array.")}

else {alert("There is no such name in the array .")}}

 

Here we have used an algorithm called linear search, according to which all the elements of an array of users are compared alternately with the sample (with n, i.e., the name that is entered by the user).

If the next element is the same as the sample, then the problem is solved (the cycle is interrupted). If the desired name is not in the array, we learn about it when we have looked all the elements of the array.

 

Task: write the script that will determine the maximal element of the numeric array.JavaScript arrays are basically used in storing multiple values in a single variable.

Create an Array in JavaScript.Here is an example, shows how to create an array in JavaScript:

var fruits = new Array( "Guava", "Apple", "Orange" );

You can also create an array in JavaScript, simply by assigning the values like this:

var fruits = [ "Guava", "Apple", "Orange" ];

The fruits[0] represents the first element which is "Guava" here, and the fruits[2] is the third element which is "Orange" here.

Display Array Element in JavaScript. Here is an example, shows how to display/print array element in JavaScript:

<!DOCTYPE html>

<html>

<head>

<title>JavaScript Array Object Example</title>

</head>

<body>

<p id="array_object_para"></p>

<script>

var cars = ["Audi", "Mercedes", "BMW"];

document.getElementById("array_object_para").innerHTML = cars[0];

</script>

</body>

</html>

 

Here is the output produced by the above Array object example in JavaScript.

 

 

Here is the live demo output of the above JavaScript Array Object example program.

Audi

Create an Array in JavaScript using new Keyword

Here is an example, shows how to create an array in JavaScript using the keyword new:

<!DOCTYPE html>

<html>

<head>

<title>JavaScript Array Object Example</title>

</head>

<body>

<p id="array_object_para2"></p>

<script>

var cars = new Array("Audi", "Mercedes", "BMW");

document.getElementById("array_object_para2").innerHTML = cars[0];

</script>

</body>

</html>

It will display the same output as produced from the above JavaScript Array Object example program.

Access Array Elements in JavaScript.To access any elements present in a array, then index the array. For example, if you want to access the first element of a array named myArr, then index this array as myArr[0]. Here is an example:

var name = cars[0];

You can also alter the value present at particular index number of the array. Here is an example, alter the value of the first element of the array cars:

cars[0] = "Opel";

JavaScript Array Object Properties.The table given below describes properties of the Array object in JavaScript.

Property Description
Constructor holds the value of the constructor function that has created the object
Length holds the number of elements in an array
Prototype adds properties and methods to the Array object

JavaScript Array Object Methods.The table given here describes methods of the Array object in JavaScript.

Method Description
concat() joins two or more arrays
join() joins all the elements of an array into a string
pop() removes the last element of an array and returns that element
push() adds new element as the last element and the returns the length of the new array
reverse() reverses the order of list of element in an array
shift() removes the first element of an array and then returns that element
slice() selects a part of an array and then returns that part as a new array
sort() sorts the elements of an array
splice() adds or removes the elements of an array
tostring() converts an array into a string and then returns the string
unshift() adds new elements to an array and then returns the new length
valueof() returns the primitive value of an Array object
Example:Sorting an Array.The sort() method sorts an array alphabetically:<!DOCTYPE html><html><body><h2>JavaScript Array Sort</h2><p>The sort() method sorts an array alphabetically.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>var fruits = ["Banana", "Orange", "Apple", "Mango"];document.getElementById("demo").innerHTML = fruits;function myFunction() {fruits.sort();document.getElementById("demo").innerHTML = fruits;}</script></body></html>        2REPORTS USING OBJECTS AND ARRAYS JAVASCRIPT2.1 Specify a reference to the result of the report, which appeared in arrays of javascript

№1

Example: Output of array elements.

<html>
<body>
<script type="text/javascript">
var x;
varmycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
{

document.write(mycars[x] + "<br />");

}
</script>
</body>
</html>

 

№2

Example:5 days a week in words, numbers. Display the result with Concate (), Join (), Popped (), Reverse (), Shift (), Sorted (). Here is an example demonstrates array in JavaScript.

 

<!DOCTYPE HTML>

<HTML>

<HEAD>

<TITLE>JavaScript Array Example</TITLE>

<SCRIPT type="text/javascript">

js_array_var1=new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday");

js_array_var2=new Array(1, 2, 3, 4, 5);

document.write("Array 1 : "+js_array_var1+"<HR/>")

document.write("Array 2 : "+js_array_var2+"<HR/>")

document.write("Concatenated Both Arrays : "+js_array_var1.concat(js_array_var2+"<HR/>"))document.write("Joined Both Arrays : "+js_array_var1.join(js_array_var2)+"<HR/>")

document.write("Array 1 Popped Out : "+js_array_var1.pop()+"<HR/>")

document.write("Reversed Array 1: "+js_array_var1.reverse()+"<HR/>")

document.write("Shifted Array 1 : "+js_array_var1.shift()+"<HR/>")

document.write("Sorted Array 1 : "+js_array_var1.sort())

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

Here is the output produced by the above JavaScript array example.

 

 

Here is the live demo output of the above Array object example in JavaScript.

 

Array 1 :Sunday,Monday,Tuesday,Wednesday,Thursday

Array 2 : 1,2,3,4,5

Concatenated Both Arrays : Sunday,Monday,Tuesday,Wednesday,Thursday,1,2,3,4,5

Joined Both Arrays : Sunday1,2,3,4,5Monday1,2,3,4,5Tuesday1,2,3,4,5Wednesday1,2,3,4,5Thursday

Array 1 Popped Out : Thursday

Reversed Array 1: Wednesday,Tuesday,Monday,Sunday

Shifted Array 1 : Wednesday

Sorted Array 1 :Monday,Sunday,Tuesday

№3Example:Numeric Sort. By default, the sort() function sorts values as strings. This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".Because of this, the sort() method will produce incorrect result when sorting numbers. You can fix this by providing a compare function: <!DOCTYPE html><html><body><h2>JavaScript Array Sort</h2><p>Click the button to sort the array in ascending order.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>var points = [40, 100, 1, 5, 25, 10];document.getElementById("demo").innerHTML = points; functionmyFunction() {points.sort(function(a, b){return a - b});document.getElementById("demo").innerHTML = points;}</script></body></html>

 

CONCLUSION

Why to Learn JavaScript ? There are the three languages, all web developers must know, these are the following:

• HTML - to define the content of web pages

• CSS - to define the layout of web pages

• JavaScript - to program the behaviour of web pages

 

 

BIBLIOGRAPHY1. Глушаков С.В. и др. Программирование Web-страниц. М.: Изд. АСТ, 2003.-387с2. Мұхамбетжанова С. Т. Компьютерлік дизайн. – Алматы, 2007.3. Балафанов Н., Бөрібаев Б. Информатикадан 30 сабақ. – Алматы, 2003.4. Смирнова И. Е., Web-дизайн бастамасы. – Санкт-Петербург, 2003.5. Гончаров А. Самоучитель HTML. – Москва, 2002.6. Информатика негіздері журналы, № 5-6 2006 жыл. – Алматы.7. Информатика и образование №2 2001 жыл. – Москва.8. Левковец, Л. Уроки компьютерной графики. Photoshop CS/, СПб.: Питер, 20059. Миронов Д. «Corel DRAW 12»: Учебный курс. –СПб.: Питер, 2004,10. Миронов Д. Компьютерная графика в дизайне. –СПб.: Питер, 2004,11. Мюррей Д.Д., Райпер У. Энциклопедия форматов графических файлов. Пер. С анг. Киев: ВНҮ, 1997,12. Панкратов Т. Photoshop7. СПб.: Питер, 200513. Влад Мержевич. Теги HTML14. Влад Мержевичcss@htmlbook.ru15. Web-сайт своими руками — И. Шапошников .: БХВ – Санкт-Петербург, 2000.

16. Дәулетқұлов А., Балапанов Е.Қ., Бөрібаев Б. Информатикадан 30 сабақ, [Текст]:Пер.с каз/Х.М. Дәулетқұлов, Е.Қ. Балапанов, Б. Бөрібаев.-1-изд.-М.:ЗАО”Издательство Алматы ИНТ”,2008.—1184с. 20 экз.

17. Ефимова . Курс компьютерной технологий [Текст]:Пер.с англ/Х.М.Ефимова,П.Д.Ефимова,Т.Р.Новиков.-2-изд.-М.:ЗАО”Издательство Рианом”,2004.—684с. 1 экз.

18. Пол Вилтон, Джереми МакпикJavascriptрукаводствапрограмиста
примерах [Текст]:Пер.с рус/Х.П.Вилтон,Дж.Макпик,Т.Р.Вилтон.-2-изд.-М.:ЗАО”Издательство Питер ”,2001.—500с. 12 экз.

19. Вайк Аллен Javascript в примерах [Текст]:Пер.сангл/Х.В.Аллен,П.Дж.Брукс,Т.Р.Далман.-2-изд.-М.:ЗАО”Издательство Питер ”,2009.—500с. 12 экз.

20. Дейтел,Х.М.,Какпрограмировать для Internet и www [Текст]:Пер.с англ/Х.М.Дейтел,П.Дж.Дейтел,Т.Р.Ниетто.-2-изд.-М.:ЗАО”Издательство БИНОМ”,2008.—1184с. 20 экз.

21. www.rambler.ru іздеу сайты

22. www.google.ru іздеу сайты

23. www.yandex.ru іздеу сайты

24.  www.KAZcity.ru іздеу сайты

25. www.TourKAZinfo.ru іздеу сайты

26. https://www.w3schools.com/asp/asp_inputforms.asp

27. https://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm

28. https://www.w3schools.com/jsref/prop_text_value.asp

29. https://www.w3schools.com/css/css_colors.asp

 










Последнее изменение этой страницы: 2018-05-10; просмотров: 193.

stydopedya.ru не претендует на авторское право материалов, которые вылажены, но предоставляет бесплатный доступ к ним. В случае нарушения авторского права или персональных данных напишите сюда...