SlideShare a Scribd company logo
Lecture3


Data Type Conversion (변하게 하다, 전환하다)

To understand what is data type conversion, and why we need data type conversion, let
us take an example.


<html>
<body>
<script language="JavaScript" type="text/javascript">

var firstNumber = prompt("Enter the first number","");
var secondNumber = prompt("Enter the second number","");
var theTotal = firstNumber + secondNumber;
document.write(firstNumber + " added to " + secondNumber + " equals " +
   theTotal);

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

What is the output, if user enters firstNumber=2 and secondNumber=3, Output should
be 5.

But if you will execute above program, you will be disappointed (실망시키다) to find that
output is 23.

Why is output 23 instead of 5?
Ans: We know that function prompt () returns a string, and if we use '+' operator with
strings, they are concatenated (사슬같이 잇다 ).

To solve (<문제 등을> 풀다, 해석하다) this problem we will take help of data type
conversion. Data type conversion means convert data type.

What is the solution?
Solution is convert String to int or float. There are 2 conversion functions parseInt() and
parseFloat().

parseInt(): This functions takes a string and convert it to an integer.
For example:
            parseInt(“123”) = 123
            parseInt(“123Abc”) = 123

parseFloat(): This function take a string and convert it to a real number.

What is the output for the following?
1. parseInt(“ABC”)
2. parseInt(“ABC123”)

Find it and I will ask you in the class.
Now, modify (수정하다 ) the above code so that it gives correct output i.e 5.

<html>
<body>
<script language="JavaScript" type="text/javascript">

var firstNumber = prompt("Enter the first number","");
var secondNumber = prompt("Enter the second number","");
var theTotal = parseInt(firstNumber) + parseInt(secondNumber);
document.write(firstNumber + " added to " + secondNumber + " equals " +
   theTotal);

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



What is NaN?

If you write document.write(parseInt(“abc”)), output will be NaN. NaN means Not a
Number.

If you use parseInt() or parseFloat() and input argument is a string that is empty or
doesn't start with a number, output is NaN.

There is a function in Javascript isNaN(x), which checks whether 'x' is NaN or not.
For example:
            isNaN(“123”) returns false
            isNaN(“ABC”) returns true
            isNaN(“123ABC”) returns true


So, Before converting any String to a number we can check beforehand (미리) whether
string consist ((부분·요소로) 되어[이루어져] 있다 ) of numbers or not. If string consist of
numbers, we can convert it otherwise ([접속사적으로] 만약 그렇지 않으면) display an error
message.

Below is a program which checks for user input. If user input is not valid, we generate
an error message.

<html>
<body>
<script language="JavaScript" type="text/javascript">

var firstNumber = prompt("Enter the first number","");
var secondNumber = prompt("Enter the second number","");
var ifn,isn;
if (isNaN(firstNumber))
      alert("this is Not a Number");
else
      ifn = parseInt(firstNumber);
if (isNaN(secondNumber))
      alert("this is not a number");
else
      isn = parseInt(secondNumber);
var theTotal = ifn+ isn;
document.write(firstNumber + " added to " + secondNumber + " equals " +
   theTotal);
</script>
</body>
</html>

Multi Dimensional Array

In my previous lecture, I taught you about 1-dim arrays. 1-dim arrays are those that
have only one index.
Like 1-dim arrays, there are 2-dim, 3-dim and multi-dim arrays.

2-dim arrays are those that have 2-dimensions.

First answer this question, What is the output of following code

<html>
<body>
<script language="JavaScript" type="text/javascript">
var a = new Array("a",2,"b",3,"c",4);
for (i=0;i<a.length;i++)
        document.write("a["+i+"] = "+a[i]+"<br>");
</script>
</body>
</html>

Two things are worth (…의 가치가 있는 ) notice (통지, 통보) in the above program
1. Unlike (같지 않은, 다른, 닮지 않은 ) arrays in other languages, arrays in Javascript can
   store values of different data types. For example:

              var a = new Array("a",2,"b",3,"c",4);

2. I told in my previous lecture also, that new keyword create an object. This means, 'a'
   is an object of Array.
   And length is a variable of Array Object in Javascript, So a.length returns length of
   array 'a'.

To understand 2-dim arrays, Let us take an example.

Suppose, we want to store a company's employee information in an array. Each
employee has
-name
-age
-address

One way to do this, is store the information in a 1-dim array sequentially (잇달아 일어나
는, 연속하는, 순차적인 ). For example:

Index               Data Stored
0                   Name1
1                   Age1
Index              Data Stored
2                  Address1
3                  Name2
4                  Age2
5                  Address2
6                  Name3
7                  Age3
8                  Address3

var employee = new
Array(“Huh”,23,”suwon”,”cho”,30,”hwaseong”,”Chong”,28,”Guro”,”chae”,40,”bundang”);

or

employee[0] = “huh”;
employee[1] = 23;
employee[2] = “suwon”;

employee[3] = “cho”;
employee[4] = 30;
employee[5] = “hwaseong”;

employee[6] = “chong”;
employee[7] = 28;
employee[8] = “guro”;

employee[9] = “chae”;
employee[10] = 40;
employee[11] = “bundang”;

employee is a 1-dim array, employee[0], employee[1], employee[2] stores information
about one employee.
empoyee[3], employee[4], employee[5] stores information about 2nd employee.

2nd way of doing this, is store the information in a 2-dim arrays.

Index          0              1           2
0              Name1          Name2       Name3
1              Age1           Age2        Age3
2              Address1       Address2    Address3

var employee = new Array(); // employee is        an array
employee[0] = new Array(); // employee[0]         is also an array
employee[1] = new Array(); // employee[1]         is also an array
employee[2] = new Array(); // employee[2]         is also an array
The first index (0) belongs ((…의) 소유물이다 ) to the employee array; the second index
(0) belongs to the employee[0] array.

employee[0][0] = “huh”;
employee[0][1] = “23”;
employee[0][2] = “suwon”;

employee[1][0] = “cho”;
employee[1][1] = “30”;
employee[1][2] = “hwaseong”;

employee[2][0] = “chong”;
employee[2][1] = “28”;
employee[2][2] = “guro”;

employee[3][0] = “chae”;
employee[3][1] = “40”;
employee[3][2] = “bundang”;

Here is the complete program

<html>
<body>

<script language="JavaScript" type="text/javascript">

var employee = new Array();

employee[0][0] = “huh”;
employee[0][1] = “23”;
employee[0][2] = “suwon”;
employee[1] = new Array();
employee[1][0] = “cho”;
employee[1][1] = “30”;
employee[1][2] = “hwaseong”;


employee[2] = new Array();
employee[2][0] = “chong”;
employee[2][1] = “28”;
employee[2][2] = “guro”;

document.write("Name : " + employee[1][0] + "<br>");
document.write("Age : " + employee[1][1] + "<br>");
document.write("Address : " + employee[1][2]);

</script>

</body>
</html>

Answer these?

var myArray = new Array(); Is it 1-dim or 2-dim array or 3-dim or 4-dim or 5-dim?
myArray[0] = new Array(); Is it 1-dim or 2-dim array or 3-dim or 4-dim or 5-dim?
myArray[0][0] = new Array(); Is it 1-dim or 2-dim array or 3-dim or 4-dim or 5-dim?
myArray[0][0][0] = new Array(); Is it 1-dim or 2-dim array or 3-dim or 4-dim or 5-dim?
myArray[0][0][0][0] = new Array(); Is it 1-dim or 2-dim array or 3-dim or 4-dim or 5-dim?

Javascript-An Object based language

In this topic, we will look at most important aspect of Javascript programing 'Objects'.
Javascript itself consist of Objects and browser also made of collection of
object.

For example:
One Javascript object that you have used is Array.
You have also used 2 objects document and window, these are objects provided by
browser.
We can create our own objects.

A brief introduction about objects

Those who have been doing programming in C++ or Java already know about objects, I
still fell the need to give an introduction about objects for those who are first time using
it.

To understand what are objects, we take an example. We will take an example of car.

How do we define a car? We define a car as a blue car with 4 wheel drive, automatic
gear, power steering, etc. Color, 4 wheel, automatic gear, 4 wheel drive, power steering
are properties of a car. If I make an object of type Car, color, automatic gear, 4 wheel
drive, power steering will be attributes or property (재산, 자산 ) of object. In Javascript,
we represent attributes as properties for an object.

How do we use a car? We turn in the key, press the pedal, change the gear, and then
move the steering. This can also be defined as behavior (행동, 거동, 행실, 품행 ) of car. In
Javascript, we represent the behavior as methods or functions of an object.

We can pass arguments to a function, for example if gear() is a function, then one of its
argument can be gear number, gear 1 or 2 or 3 or 4 or reverse.
Similarly, speed() function can return me the speed of the car.
Or OilLeft() function can return the amount of oil left in the car.

If we want to define an object for car, we need to defined attributes and functions for
the car object. In Object based programming, we try to model real life things by an
Object. And objects are defined by their attributes and functions.

Basic definition of an Object is “A thing with attributes and functions”.

Take an example, We used array.length which returns length of the array, now array is
an object and length is an attribute of array object. Length attribute of array object,
returns number of elements stored in the array.
Let us do to anatomy (해부;해부학;해부술 ) of Array object.

We create an array by the statement
var num = new Array(7, 6, 5, 4, 3, 2, 1, 0, 8, 9);

'num' is a variable name. In the above example, right hand side of the statement create




an array in memory.

Starting address of the array is 100. 'num' stores only the starting address of array i.e.
'num' stores value 100.

new is a keyword in Javascript for creating object. In the above example, we are
creating an object of type Array. Object is created in memory and its starting address is
100 which is stored in variable 'num'.

Let us take another example of using Date Object

var d = new Date(“1 Jan 2000”);

'd' is a variable which can store an integer, character, string etc, in the above example
variable 'd' stores address of an object of type Date.

'new' is a keyword that creates an object. In the above example we are creating an
object of type Date. The object of type Date takes some space in memory and has a
starting address. 'd' stores starting address of object of type Date.

Let us try to understand more about objects and variables.
I am starting with an example of simple variables.

1.   var a = 10;
2.   var b = a;
3.   document.write(a);   // Output is 10
4.   document.write(b);   // Output is 10
5.   b = 20;
6.   document.write(a);   // Output is 10
7.   document.write(b);   // Output is 20

a and b are 2 different variables.
Line 1, variable a stores value 10.
Line 2, variable b also stores the value value stored in a (10). So b also stores value 10.
Line 3 output is 10 and line 4 output is 20.
Line 5, we change the value stored in b. New value stored in b is 20 now. But value
stored in a does not change which is still 10.
Line 6 output is 10, because value stored in a does not change.
Line 7 output is 20, because value stored in b changes from 10 to 20.

The above was a simple example using variables. Next we take an example using
objects.

   1. var a = new Array(7, 6, 5);




   2. var b = a;




3. document.write(a[0] + “ ”+ a[1]+ “ ”+ a[2]); // output is 7 6 5
4. document.write(b[0] + “ ”+ b[1]+ “ ”+ b[2]); // output is yeh
5. b[1] = 3;




6. document.write(a[0] + “ ”+ a[1]+ “ ”+ a[2]); // output is 7 3 5
7. document.write(b[0] + “ ”+ b[1]+ “ ”+ b[2]);// output is 7 3 5

Line 1, creates an object of type array and stores the address of object in a. Suppose
Object of type array has starting address 100, then a stores 100.

Line 2, variable b gets the value stores in a, which is 100. i.e. B = 100.

Line 3, output is 7 6 5.

Line 4, output is 7 6 5, because b also contain the address 100 which is same as
address stored in a.
Line 5. We change the value if b[1] to 2, because a and b both contain the same address
b[1] and a[1] refer to same location of memory.

Line 6 output is 7 3 5 and line 7 output is 7 3 5.

Using an Object Properties and Methods

Every object provide (지급하다) some methods and properties. For example, we can find the length of the array,
For example:

var a = new Array( 7 , 6 , 5);
var len = a.length; // output is 3

length is a property of Array object. It returns the length of the array.
Address of Array object is stored in the variable a. So a can access all the properties of Array object.

a . name of property

Simillary,
a . name of function(), here function can be replaced by actual function name.
For example
Date d = new Date(“15 Aug 1953”)
dd = d.getDate(); // dd = 31

getDate() is a function of Date Object.


Primitives and Objects

You should now have a good idea about the difference between primitive (원시의, 초기의;
태고의, 옛날의 ) data, such as numbers and strings, and object data, such as Dates and
Arrays.
We have string, number and boolean data types. In fact there are String, Number, and
Boolean objects corresponding (유사한 ) to the three string, number, and Boolean
primitive data types. For example, to create a String object containing the text "I'm a
String object," we can use
var myString = new String("I'm a String object");

The String object has the length property just as the Array object does. This returns the
number of characters in the String object. For example
var lengthOfString = myString.length;

would store the data 19 in the variable lengthOfString.
But what if we had declared a primitive string called mySecondString holding the text
"I'm a _primitive string" like this:
var mySecondString = "I'm a primitive string";

and wanted to know how many characters could be found in this primitive string?
So, for our primitive string mySecondString, we can use the length property of the
String object to find out the number of characters it contains. For example
var lengthOfSecondString = mySecondString.length;

would store the data 22 in the variable lengthOfSecondString
If we declare a primitive string and then treat it as an object, such as by trying to access
one of its methods or properties, JavaScript would know that the operation we're trying
to do won't work if it's a primitive string. It will only work if it's an object; for example, it
would be valid if it were a String object. In this case, JavaScript converts the plain
text string into a temporary String object, just for that operation.

More Related Content

What's hot (20)

PDF
Functional es6
Natalia Zaslavskaya
 
ODP
Scala introduction
Alf Kristian Støyle
 
PPT
JavaScript Arrays
Reem Alattas
 
PPTX
Python 표준 라이브러리
용 최
 
PDF
Lodash js
LearningTech
 
PDF
Underscore.js
timourian
 
PPTX
Lecture06 methods for-making_data_structures_v2
Hariz Mustafa
 
PPTX
Learn python - for beginners - part-2
RajKumar Rampelli
 
PPTX
Java script arrays
Frayosh Wadia
 
PDF
Java 8 DOs and DON'Ts - javaBin Oslo May 2015
Fredrik Vraalsen
 
PPTX
Giving Clarity to LINQ Queries by Extending Expressions R2
Ed Charbeneau
 
PPT
Csharp4 arrays and_tuples
Abed Bukhari
 
PPTX
Basics of Python programming (part 2)
Pedro Rodrigues
 
PDF
Objective-C for Java developers
Fábio Bernardo
 
PDF
Chaining and function composition with lodash / underscore
Nicolas Carlo
 
PDF
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
PDF
Groovy
congcong wang
 
PPTX
Pragmatic metaprogramming
Mårten Rånge
 
PDF
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
PPTX
Ggplot2 v3
Josh Doyle
 
Functional es6
Natalia Zaslavskaya
 
Scala introduction
Alf Kristian Støyle
 
JavaScript Arrays
Reem Alattas
 
Python 표준 라이브러리
용 최
 
Lodash js
LearningTech
 
Underscore.js
timourian
 
Lecture06 methods for-making_data_structures_v2
Hariz Mustafa
 
Learn python - for beginners - part-2
RajKumar Rampelli
 
Java script arrays
Frayosh Wadia
 
Java 8 DOs and DON'Ts - javaBin Oslo May 2015
Fredrik Vraalsen
 
Giving Clarity to LINQ Queries by Extending Expressions R2
Ed Charbeneau
 
Csharp4 arrays and_tuples
Abed Bukhari
 
Basics of Python programming (part 2)
Pedro Rodrigues
 
Objective-C for Java developers
Fábio Bernardo
 
Chaining and function composition with lodash / underscore
Nicolas Carlo
 
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Pragmatic metaprogramming
Mårten Rånge
 
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
Ggplot2 v3
Josh Doyle
 

Viewers also liked (19)

PDF
Resolution
H K
 
DOC
Appendix css
H K
 
DOC
Java script advanced frame
H K
 
PDF
Assignment sw solution
H K
 
PPT
Html dom part-ii
H K
 
PDF
Solution3
H K
 
PDF
Java script introducation & basics
H K
 
PPT
Ch04
H K
 
DOC
Html basics 4 anchor list
H K
 
PDF
Assignment sw
H K
 
DOC
Html basics 8 frame
H K
 
PDF
Ip protocol tedting
H K
 
DOC
Lecture3layered archi
H K
 
PDF
Week32
H K
 
PDF
Lecture20 tcp
H K
 
PPT
Week4142
H K
 
DOC
Css 2
H K
 
PPTX
Logic
H K
 
PPT
Proof
H K
 
Resolution
H K
 
Appendix css
H K
 
Java script advanced frame
H K
 
Assignment sw solution
H K
 
Html dom part-ii
H K
 
Solution3
H K
 
Java script introducation & basics
H K
 
Ch04
H K
 
Html basics 4 anchor list
H K
 
Assignment sw
H K
 
Html basics 8 frame
H K
 
Ip protocol tedting
H K
 
Lecture3layered archi
H K
 
Week32
H K
 
Lecture20 tcp
H K
 
Week4142
H K
 
Css 2
H K
 
Logic
H K
 
Proof
H K
 
Ad

Similar to Java script objects 1 (20)

PPT
Java căn bản - Chapter10
Vince Vo
 
PPTX
07+08slide.pptx
MURADSANJOUM
 
PPTX
CAP615-Unit1.pptx
SatyajeetGaur3
 
PPT
Lecture no 9.ppt operating system semester four
VaibhavBhagwat18
 
PPT
ajava arrays topic brief explanation data
VenkatasaireddyMarth
 
PPT
Data Structure In C#
Shahzad
 
PPTX
Introduction to Client-Side Javascript
Julie Iskander
 
KEY
CoffeeScript - A Rubyist's Love Affair
Mark
 
PPSX
Javascript variables and datatypes
Varun C M
 
PDF
iRODS Rule Language Cheat Sheet
Samuel Lampa
 
PDF
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
PDF
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
PDF
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Arrays and function basic c programming notes
GOKULKANNANMMECLECTC
 
PDF
Assignment of Advanced data structure and algorithms..pdf
vishuv3466
 
PDF
Assignment of Advanced data structure and algorithms ..pdf
vishuv3466
 
PDF
Assignment of Advanced data structure and algorithm ..pdf
vishuv3466
 
PPT
POLITEKNIK MALAYSIA
Aiman Hud
 
PPS
CS101- Introduction to Computing- Lecture 26
Bilal Ahmed
 
PPTX
Javascript 101
Shlomi Komemi
 
Java căn bản - Chapter10
Vince Vo
 
07+08slide.pptx
MURADSANJOUM
 
CAP615-Unit1.pptx
SatyajeetGaur3
 
Lecture no 9.ppt operating system semester four
VaibhavBhagwat18
 
ajava arrays topic brief explanation data
VenkatasaireddyMarth
 
Data Structure In C#
Shahzad
 
Introduction to Client-Side Javascript
Julie Iskander
 
CoffeeScript - A Rubyist's Love Affair
Mark
 
Javascript variables and datatypes
Varun C M
 
iRODS Rule Language Cheat Sheet
Samuel Lampa
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Arrays and function basic c programming notes
GOKULKANNANMMECLECTC
 
Assignment of Advanced data structure and algorithms..pdf
vishuv3466
 
Assignment of Advanced data structure and algorithms ..pdf
vishuv3466
 
Assignment of Advanced data structure and algorithm ..pdf
vishuv3466
 
POLITEKNIK MALAYSIA
Aiman Hud
 
CS101- Introduction to Computing- Lecture 26
Bilal Ahmed
 
Javascript 101
Shlomi Komemi
 
Ad

More from H K (20)

PDF
Assignment4
H K
 
DOCX
Assignment3
H K
 
PDF
Induction
H K
 
PDF
Solution2
H K
 
DOCX
Mid-
H K
 
PDF
Assignment4
H K
 
PDF
Assignment4
H K
 
PDF
Dm assignment3
H K
 
DOCX
Assignment description
H K
 
PDF
Dm assignment2
H K
 
PDF
Set
H K
 
PDF
Dm assignment1
H K
 
DOCX
Introduction
H K
 
PDF
Assignment 2 sol
H K
 
PDF
Violinphoenix
H K
 
PDF
Ie project
H K
 
PDF
Assignment cn subnetting
H K
 
PDF
Assignment uplaodfile
H K
 
PDF
Assignment sw
H K
 
PDF
Assignment cn tl
H K
 
Assignment4
H K
 
Assignment3
H K
 
Induction
H K
 
Solution2
H K
 
Mid-
H K
 
Assignment4
H K
 
Assignment4
H K
 
Dm assignment3
H K
 
Assignment description
H K
 
Dm assignment2
H K
 
Set
H K
 
Dm assignment1
H K
 
Introduction
H K
 
Assignment 2 sol
H K
 
Violinphoenix
H K
 
Ie project
H K
 
Assignment cn subnetting
H K
 
Assignment uplaodfile
H K
 
Assignment sw
H K
 
Assignment cn tl
H K
 

Recently uploaded (20)

PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
community health nursing question paper 2.pdf
Prince kumar
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 

Java script objects 1

  • 1. Lecture3 Data Type Conversion (변하게 하다, 전환하다) To understand what is data type conversion, and why we need data type conversion, let us take an example. <html> <body> <script language="JavaScript" type="text/javascript"> var firstNumber = prompt("Enter the first number",""); var secondNumber = prompt("Enter the second number",""); var theTotal = firstNumber + secondNumber; document.write(firstNumber + " added to " + secondNumber + " equals " + theTotal); </script> </body> </html> What is the output, if user enters firstNumber=2 and secondNumber=3, Output should be 5. But if you will execute above program, you will be disappointed (실망시키다) to find that output is 23. Why is output 23 instead of 5? Ans: We know that function prompt () returns a string, and if we use '+' operator with strings, they are concatenated (사슬같이 잇다 ). To solve (<문제 등을> 풀다, 해석하다) this problem we will take help of data type conversion. Data type conversion means convert data type. What is the solution? Solution is convert String to int or float. There are 2 conversion functions parseInt() and parseFloat(). parseInt(): This functions takes a string and convert it to an integer. For example: parseInt(“123”) = 123 parseInt(“123Abc”) = 123 parseFloat(): This function take a string and convert it to a real number. What is the output for the following? 1. parseInt(“ABC”) 2. parseInt(“ABC123”) Find it and I will ask you in the class.
  • 2. Now, modify (수정하다 ) the above code so that it gives correct output i.e 5. <html> <body> <script language="JavaScript" type="text/javascript"> var firstNumber = prompt("Enter the first number",""); var secondNumber = prompt("Enter the second number",""); var theTotal = parseInt(firstNumber) + parseInt(secondNumber); document.write(firstNumber + " added to " + secondNumber + " equals " + theTotal); </script> </body> </html> What is NaN? If you write document.write(parseInt(“abc”)), output will be NaN. NaN means Not a Number. If you use parseInt() or parseFloat() and input argument is a string that is empty or doesn't start with a number, output is NaN. There is a function in Javascript isNaN(x), which checks whether 'x' is NaN or not. For example: isNaN(“123”) returns false isNaN(“ABC”) returns true isNaN(“123ABC”) returns true So, Before converting any String to a number we can check beforehand (미리) whether string consist ((부분·요소로) 되어[이루어져] 있다 ) of numbers or not. If string consist of numbers, we can convert it otherwise ([접속사적으로] 만약 그렇지 않으면) display an error message. Below is a program which checks for user input. If user input is not valid, we generate an error message. <html> <body> <script language="JavaScript" type="text/javascript"> var firstNumber = prompt("Enter the first number",""); var secondNumber = prompt("Enter the second number",""); var ifn,isn; if (isNaN(firstNumber)) alert("this is Not a Number"); else ifn = parseInt(firstNumber); if (isNaN(secondNumber)) alert("this is not a number"); else isn = parseInt(secondNumber); var theTotal = ifn+ isn; document.write(firstNumber + " added to " + secondNumber + " equals " + theTotal);
  • 3. </script> </body> </html> Multi Dimensional Array In my previous lecture, I taught you about 1-dim arrays. 1-dim arrays are those that have only one index. Like 1-dim arrays, there are 2-dim, 3-dim and multi-dim arrays. 2-dim arrays are those that have 2-dimensions. First answer this question, What is the output of following code <html> <body> <script language="JavaScript" type="text/javascript"> var a = new Array("a",2,"b",3,"c",4); for (i=0;i<a.length;i++) document.write("a["+i+"] = "+a[i]+"<br>"); </script> </body> </html> Two things are worth (…의 가치가 있는 ) notice (통지, 통보) in the above program 1. Unlike (같지 않은, 다른, 닮지 않은 ) arrays in other languages, arrays in Javascript can store values of different data types. For example: var a = new Array("a",2,"b",3,"c",4); 2. I told in my previous lecture also, that new keyword create an object. This means, 'a' is an object of Array. And length is a variable of Array Object in Javascript, So a.length returns length of array 'a'. To understand 2-dim arrays, Let us take an example. Suppose, we want to store a company's employee information in an array. Each employee has -name -age -address One way to do this, is store the information in a 1-dim array sequentially (잇달아 일어나 는, 연속하는, 순차적인 ). For example: Index Data Stored 0 Name1 1 Age1
  • 4. Index Data Stored 2 Address1 3 Name2 4 Age2 5 Address2 6 Name3 7 Age3 8 Address3 var employee = new Array(“Huh”,23,”suwon”,”cho”,30,”hwaseong”,”Chong”,28,”Guro”,”chae”,40,”bundang”); or employee[0] = “huh”; employee[1] = 23; employee[2] = “suwon”; employee[3] = “cho”; employee[4] = 30; employee[5] = “hwaseong”; employee[6] = “chong”; employee[7] = 28; employee[8] = “guro”; employee[9] = “chae”; employee[10] = 40; employee[11] = “bundang”; employee is a 1-dim array, employee[0], employee[1], employee[2] stores information about one employee. empoyee[3], employee[4], employee[5] stores information about 2nd employee. 2nd way of doing this, is store the information in a 2-dim arrays. Index 0 1 2 0 Name1 Name2 Name3 1 Age1 Age2 Age3 2 Address1 Address2 Address3 var employee = new Array(); // employee is an array employee[0] = new Array(); // employee[0] is also an array employee[1] = new Array(); // employee[1] is also an array employee[2] = new Array(); // employee[2] is also an array
  • 5. The first index (0) belongs ((…의) 소유물이다 ) to the employee array; the second index (0) belongs to the employee[0] array. employee[0][0] = “huh”; employee[0][1] = “23”; employee[0][2] = “suwon”; employee[1][0] = “cho”; employee[1][1] = “30”; employee[1][2] = “hwaseong”; employee[2][0] = “chong”; employee[2][1] = “28”; employee[2][2] = “guro”; employee[3][0] = “chae”; employee[3][1] = “40”; employee[3][2] = “bundang”; Here is the complete program <html> <body> <script language="JavaScript" type="text/javascript"> var employee = new Array(); employee[0][0] = “huh”; employee[0][1] = “23”; employee[0][2] = “suwon”; employee[1] = new Array(); employee[1][0] = “cho”; employee[1][1] = “30”; employee[1][2] = “hwaseong”; employee[2] = new Array(); employee[2][0] = “chong”; employee[2][1] = “28”; employee[2][2] = “guro”; document.write("Name : " + employee[1][0] + "<br>"); document.write("Age : " + employee[1][1] + "<br>"); document.write("Address : " + employee[1][2]); </script> </body> </html> Answer these? var myArray = new Array(); Is it 1-dim or 2-dim array or 3-dim or 4-dim or 5-dim? myArray[0] = new Array(); Is it 1-dim or 2-dim array or 3-dim or 4-dim or 5-dim?
  • 6. myArray[0][0] = new Array(); Is it 1-dim or 2-dim array or 3-dim or 4-dim or 5-dim? myArray[0][0][0] = new Array(); Is it 1-dim or 2-dim array or 3-dim or 4-dim or 5-dim? myArray[0][0][0][0] = new Array(); Is it 1-dim or 2-dim array or 3-dim or 4-dim or 5-dim? Javascript-An Object based language In this topic, we will look at most important aspect of Javascript programing 'Objects'. Javascript itself consist of Objects and browser also made of collection of object. For example: One Javascript object that you have used is Array. You have also used 2 objects document and window, these are objects provided by browser. We can create our own objects. A brief introduction about objects Those who have been doing programming in C++ or Java already know about objects, I still fell the need to give an introduction about objects for those who are first time using it. To understand what are objects, we take an example. We will take an example of car. How do we define a car? We define a car as a blue car with 4 wheel drive, automatic gear, power steering, etc. Color, 4 wheel, automatic gear, 4 wheel drive, power steering are properties of a car. If I make an object of type Car, color, automatic gear, 4 wheel drive, power steering will be attributes or property (재산, 자산 ) of object. In Javascript, we represent attributes as properties for an object. How do we use a car? We turn in the key, press the pedal, change the gear, and then move the steering. This can also be defined as behavior (행동, 거동, 행실, 품행 ) of car. In Javascript, we represent the behavior as methods or functions of an object. We can pass arguments to a function, for example if gear() is a function, then one of its argument can be gear number, gear 1 or 2 or 3 or 4 or reverse. Similarly, speed() function can return me the speed of the car. Or OilLeft() function can return the amount of oil left in the car. If we want to define an object for car, we need to defined attributes and functions for the car object. In Object based programming, we try to model real life things by an Object. And objects are defined by their attributes and functions. Basic definition of an Object is “A thing with attributes and functions”. Take an example, We used array.length which returns length of the array, now array is an object and length is an attribute of array object. Length attribute of array object, returns number of elements stored in the array.
  • 7. Let us do to anatomy (해부;해부학;해부술 ) of Array object. We create an array by the statement var num = new Array(7, 6, 5, 4, 3, 2, 1, 0, 8, 9); 'num' is a variable name. In the above example, right hand side of the statement create an array in memory. Starting address of the array is 100. 'num' stores only the starting address of array i.e. 'num' stores value 100. new is a keyword in Javascript for creating object. In the above example, we are creating an object of type Array. Object is created in memory and its starting address is 100 which is stored in variable 'num'. Let us take another example of using Date Object var d = new Date(“1 Jan 2000”); 'd' is a variable which can store an integer, character, string etc, in the above example variable 'd' stores address of an object of type Date. 'new' is a keyword that creates an object. In the above example we are creating an object of type Date. The object of type Date takes some space in memory and has a starting address. 'd' stores starting address of object of type Date. Let us try to understand more about objects and variables. I am starting with an example of simple variables. 1. var a = 10; 2. var b = a; 3. document.write(a); // Output is 10 4. document.write(b); // Output is 10 5. b = 20; 6. document.write(a); // Output is 10 7. document.write(b); // Output is 20 a and b are 2 different variables. Line 1, variable a stores value 10. Line 2, variable b also stores the value value stored in a (10). So b also stores value 10. Line 3 output is 10 and line 4 output is 20.
  • 8. Line 5, we change the value stored in b. New value stored in b is 20 now. But value stored in a does not change which is still 10. Line 6 output is 10, because value stored in a does not change. Line 7 output is 20, because value stored in b changes from 10 to 20. The above was a simple example using variables. Next we take an example using objects. 1. var a = new Array(7, 6, 5); 2. var b = a; 3. document.write(a[0] + “ ”+ a[1]+ “ ”+ a[2]); // output is 7 6 5 4. document.write(b[0] + “ ”+ b[1]+ “ ”+ b[2]); // output is yeh 5. b[1] = 3; 6. document.write(a[0] + “ ”+ a[1]+ “ ”+ a[2]); // output is 7 3 5 7. document.write(b[0] + “ ”+ b[1]+ “ ”+ b[2]);// output is 7 3 5 Line 1, creates an object of type array and stores the address of object in a. Suppose Object of type array has starting address 100, then a stores 100. Line 2, variable b gets the value stores in a, which is 100. i.e. B = 100. Line 3, output is 7 6 5. Line 4, output is 7 6 5, because b also contain the address 100 which is same as address stored in a.
  • 9. Line 5. We change the value if b[1] to 2, because a and b both contain the same address b[1] and a[1] refer to same location of memory. Line 6 output is 7 3 5 and line 7 output is 7 3 5. Using an Object Properties and Methods Every object provide (지급하다) some methods and properties. For example, we can find the length of the array, For example: var a = new Array( 7 , 6 , 5); var len = a.length; // output is 3 length is a property of Array object. It returns the length of the array. Address of Array object is stored in the variable a. So a can access all the properties of Array object. a . name of property Simillary, a . name of function(), here function can be replaced by actual function name. For example Date d = new Date(“15 Aug 1953”) dd = d.getDate(); // dd = 31 getDate() is a function of Date Object. Primitives and Objects You should now have a good idea about the difference between primitive (원시의, 초기의; 태고의, 옛날의 ) data, such as numbers and strings, and object data, such as Dates and Arrays. We have string, number and boolean data types. In fact there are String, Number, and Boolean objects corresponding (유사한 ) to the three string, number, and Boolean primitive data types. For example, to create a String object containing the text "I'm a String object," we can use var myString = new String("I'm a String object"); The String object has the length property just as the Array object does. This returns the number of characters in the String object. For example var lengthOfString = myString.length; would store the data 19 in the variable lengthOfString. But what if we had declared a primitive string called mySecondString holding the text "I'm a _primitive string" like this: var mySecondString = "I'm a primitive string"; and wanted to know how many characters could be found in this primitive string?
  • 10. So, for our primitive string mySecondString, we can use the length property of the String object to find out the number of characters it contains. For example var lengthOfSecondString = mySecondString.length; would store the data 22 in the variable lengthOfSecondString If we declare a primitive string and then treat it as an object, such as by trying to access one of its methods or properties, JavaScript would know that the operation we're trying to do won't work if it's a primitive string. It will only work if it's an object; for example, it would be valid if it were a String object. In this case, JavaScript converts the plain text string into a temporary String object, just for that operation.