Object initialization in JavaScript refers to the process of creating an object and initializing its properties and values. One common way to initialize an object is by using an object literal, which is a comma-separated list of name-value pairs enclosed in curly braces. For example:
var person = {
name: "John",
age: 30,
city: "New York"
};
Example:
<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>
<script>
michael = {name: "Michael", lastname: "Smith", ssn: 111222};
samantha = {name: "Samantha", lastname: "Fox", ssn: 555444};
document.write(michael.ssn + "<br>");
alert(samantha.name + " "+ samantha.lastname);
</script>
</body>
</html>
This code initializes two objects, michael
and samantha
, using object literal notation in JavaScript.
Each object is defined as a set of key-value pairs enclosed in curly braces, where each key represents a property of the object and each value is the corresponding value of that property.
For example, michael
has three properties: name
, lastname
, and ssn
, with the corresponding values of "Michael", "Smith", and 111222, respectively. Similarly, samantha
has the same properties with different values.
The document.write
method is used to output the ssn
property of michael
, while the alert
function displays the name
and lastname
properties of samantha
.
This is a simple way of initializing objects in JavaScript using object literal notation. It is a compact and efficient way of creating objects with properties and values, especially for small and simple objects.
<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>
<script>
var plang = new Array("PHP", "Python", "C++", "C");
document.write(plang[0] + "<br>");
document.write(plang[1] + "<br>");
document.write(plang[2] + "<br>");
document.write(plang[3] + "<br>");
</script>
</body>
</html>
The above JavaScript code creates an array named plang
containing four elements: "PHP", "Python", "C++", and "C". It then uses the document.write
method to output each element of the array to the web page. The array elements are accessed using their indexes, which start at 0. So plang[0]
returns the first element of the array ("PHP"), plang[1]
returns the second element ("Python"), and so on.
No comments:
Post a Comment