Vous êtes sur la page 1sur 30

JavaScriptArrays

Syntax:
vararray-name= [item1,item2, ...];
Type: Object
Using the JavaScript Keyword new
varcars
=newArray("Saab","Volvo","BMW");
Access the Elements of an Array
varcars = ["Saab","Volvo","BMW"];
document.getElementById("demo").inn
erHTML = cars[0];

Access the Full Array


varcars = ["Saab","Volvo","BMW"];
document.getElementById("demo").i
nnerHTML = cars;
Array Elements Can Be
heterogeneous

Array Properties and Methods


varx = cars.length;// The length property
returns the number of elements
vary = cars.sort();// The sort() method sorts
arrays
By default, the sort() function sorts values
asstrings.
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.

Looping Array Elements


varfruits, text, fLen, i;
fruits =
["Banana","Orange","Apple","Mang
o"];
fLen = fruits.length;
text = ";
for(i =0; i < fLen; i++) {
text += fruits[i];
}

Adding Array Elements


varfruits =
["Banana","Orange","Apple","Mango"];
fruits.push("Lemon"); // adds a
new element (Lemon) to fruits
New element can also be added to an
array using the length property:
varfruits =
["Banana","Orange","Apple","Mango"];
fruits[fruits.length] ="Lemon";// adds a
new element (Lemon) to fruits

Adding elements with high indexes can create


undefined "holes" in an array:
varfruits = ["Banana","Orange","Apple","Mango"];
fruits[6] ="Lemon"; // adds a new
element (Lemon) to fruits
Associative Arrays
Many programming languages support arrays with
named indexes.
Arrays with named indexes are called associative
arrays (or hashes).
JavaScript doesnotsupport arrays with named
indexes.
In JavaScript,arraysalways usenumbered
indexes.

Associative Arrays
Associative arrays have an index that is not
necessarily an integer, and can be sparsely
populated. The index for an associative
array is called thekey, and its type is called
theKeyType.
Associative arrays are declared by placing
theKeyTypewithin the[ ]of an array
declaration:
int[string] aa; // Associative array of ints
that are // indexed by string keys. // The
KeyType is string. aa["hello"] = 3; // set
value associated with key "hello" to 3

Difference Between Arrays and Objects


In JavaScript,arraysusenumbered
indexes.
In JavaScript,objectsusenamed
indexes.
Arrays are a special kind of objects, with
numbered indexes.
Use
useobjectswhen you want the element
names to bestrings (text).
usearrayswhen you want the element
names to benumbers.

JavaScriptObjects

In JavaScript, almost "everything" is an object.


Booleans can be objects (or primitive data treated as
objects)
Numbers can be objects (or primitive data treated as
objects)
Strings can be objects (or primitive data treated as objects)
Dates are always objects
Maths are always objects
Regular expressions are always objects
Arrays are always objects
Functions are always objects
Objects are objects
In JavaScript, all values, except primitive values, are
objects.
Primitive values are: strings ("John Doe"), numbers (3.14),
true, false, null, and undefined.

Objects are Variables Containing


Variables
varperson ="John Doe";
The values are written asname :
valuepairs (name and value
separated by a colon).
varperson = {firstName:"John",
lastName:"Doe", age:50,
eyeColor:"blue"};
Object Properties
The name:values pairs (in JavaScript

Accessing Object Properties


You can access object properties in
two ways:
objectName.propertyName
or
objectName["propertyName"]
Eg
document.getElementById("demo").i
nnerHTML = person["firstName"] + "
" + person["lastName"];

Object Methods
Methods are actions that can be
performed on objects. A method is
actually a function definition stored
as a property value.
You access an object method with
the following syntax:
objectName.methodName()
If you access the fullName method,
without (), it will return the function
definition:
name = person.fullName;

var person = {

firstName: "John",

lastName : "Doe",

id
: 5566,

fullName : function() {

return this.firstName + " " +


this.lastName;

JavaScript Functions

A JavaScript function is a block of code designed


to perform a particular task.
Syntax
A JavaScript function is defined with the function
keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits,
underscores, and dollar signs (same rules as
variables).
The parentheses may include parameter names
separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is
placed inside curly brackets: {}

Function parameters are the names listed in


the function definition.
Function arguments are the real values
received by the function when it is invoked.
Function Return
When JavaScript reaches a return statement,
the function will stop executing.
If the function was invoked from a statement,
JavaScript will "return" to execute the code
after the invoking statement.
Functions often compute a return value. The
return value is "returned" back to the "caller":

<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML =
myFunction(4, 3);
</script>
var x = myFunction(4, 3); // Function is called,
return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the
product of a and b
}

Functions Used as Variable Values


Functions can be used the same way as you
use variables, in all types of formulas,
assignments, and calculations. i.e. instead of
using a variable to store the return value of a
function:
var x = toCelsius(77);
var text = "The temperature is " + x + "
Celsius";
You can use the function directly, as a
variable value:
var text = "The temperature is " +
toCelsius(77) + " Celsius";

Dialog Box

JavaScript has three kind of popup boxes:


Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make
sure information comes through to the user.
When an alert box pops up, the user will have
to click "OK" to proceed.
Syntax:
window.alert("sometext");
The window.alert() method can be written
without the window prefix.
alert("I am an alert box!");

<button onclick="myFunction()">Try
it</button>
<script>
function myFunction() {

alert("I am an alert box!");


}
</script>

Confirm Box
A confirm box is often used if you
want the user to verify or accept
something.
When a confirm box pops up, the
user will have to click either "OK" or
"Cancel" to proceed.
If the user clicks "OK", the box
returns true. If the user clicks
"Cancel", the box returns false.
Syntax
window.confirm("sometext");

The window.confirm() method can be written without the


window prefix.
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {

var x;

if (confirm("Press a button!") == true) {

x = "You pressed OK!";

} else {

x = "You pressed Cancel!";

document.getElementById("demo").innerHTML =
x;
}
</script>

Prompt Box
A prompt box is often used if you want the
user to input a value before entering a page.
When a prompt box pops up, the user will
have to click either "OK" or "Cancel" to
proceed after entering an input value.
If the user clicks "OK" the box returns the
input value. If the user clicks "Cancel" the box
returns null.
Syntax
window.prompt("sometext","defaultText");
The window.prompt() method can be
written without the window prefix.

<button onclick="myFunction()">Try it</button>


<p id="demo"></p>
<script>
function myFunction() {
var person = prompt("Please enter your
name", abc");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
}
</script>

Line Breaks
To display line breaks inside a popup
box, use a back-slash followed by the
character n.
<button onclick="myFunction()">Try
it</button>
<script>
function myFunction() {

alert("Hello\nHow are you?");


}
</script>

innerHTML
By manipulating an element's innerHtml you'll be
able to change your text and HTML as much as
you like.
Each HTML element has an innerHTML property
that defines both the HTML code and the text that
occurs between that element's opening and
closing tag. By changing an element's innerHTML
after some user interaction, you can make much
more interactive pages.
However, using innerHTML requires some
preparation if you want to be able to use it easily
and reliably. First, you must give the element you
wish to change an id. With that id in place you will
be able to use the getElementById function,

Vous aimerez peut-être aussi