js review note day6

Keywords: Javascript Attribute less

JavaScript HTML DOM element (node)

Create new HTML elements

<div id="div1">
<p id="p1"> This is a paragraph. </p>
<p id="p2"> This is another paragraph. </p>
</div>

<script>
var para=document.createElement("p");
var node=document.createTextNode("This is a new paragraph.");
para.appendChild(node);

var element=document.getElementById("div1");
element.appendChild(para);
</script>

Delete existing HTML elements

<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>

JavaScript object

Everything in JavaScript is an object: a string, a number, an array, a function...

Everything is an object.

JavaScript provides multiple built-in objects, such as String, Date, Array, and so on. Objects are only special data types with attributes and methods.

  • Boolean type can be an object.
  • A numeric type can be an object.
  • A string can also be an object
  • Date is an object
  • Mathematics and regular expressions are also objects.
  • An array is an object
  • Even functions can be objects.

Method of accessing objects

The method is an action that can be performed on an object.


Create JavaScript objects

With JavaScript, you can define and create your own objects.

There are two different ways to create new objects:

  • Define and create instances of objects
  • Use functions to define objects, and then create new object instances

person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";

Alternative grammar (using object literals):

person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

Using Object Constructor

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}

Create JavaScript object instances

var myFather=new person("John","Doe",50,"blue");

var myMother=new person("Sally","Rally",48,"green");


Add methods to JavaScript objects

A method is simply a function attached to an object.

Method of defining objects within constructor functions:

function person(firstname,lastname,age,eyecolor)

{

this.firstname=firstname;

this.lastname=lastname;

this.age=age;

this.eyecolor=eyecolor;


this.changeName=changeName;

function changeName(name)

{

this.lastname=name;

}

}


myMother.changeName("Doe"); the value of the //changeName() function name is assigned to the last name property of the person.


JavaScript class

JavaScript is an object-oriented language, but JavaScript does not use classes.

In JavaScript, classes are not created, nor are objects created through classes (as in other object-oriented languages).

JavaScript is prototype-based, not class-based.

<script>
function myFunction(){
	var x;
	var txt="";
	var person={fname:"Bill",lname:"Gates",age:56}; 
	for (x in person){
		txt=txt + person[x];
	}
	document.getElementById("demo").innerHTML=txt;
}
</script>


JavaScript Number Object

JavaScript has only one numeric type.

Numbers can be written using or without decimal points.

All JavaScript numbers are 64 bits

Accuracy of integers (not using decimal points or exponential counting) is up to 15 bits.


Octal and hexadecimal

If the prefix is 0, JavaScript interprets numeric constants as octal numbers, and if the prefix is 0 and "x", as hexadecimal numbers.

//The toString() method is used to output hexadecimal, octal and binary.
var myNumber=128;
myNumber.toString(16);   // Return to 80
myNumber.toString(8);    // Return to 200
myNumber.toString(2);    // Return 10000000

Infinity

When the result of a numeric operation exceeds the numeric upper limit (overflow) that JavaScript can represent, the result is a special infinity value, expressed as Infinity in JavaScript. Similarly, when the value of a negative number exceeds the range of negative numbers that JavaScript can represent, the result is negative infinity, which is represented in JavaScript as - Infinity. The behavioral properties of infinite values are consistent with what we expect: based on their addition, subtraction, multiplication and division operations, the results are still infinite (with positive and negative signs, of course).


NaN - Non-numeric Value

NaN attributes are special values representing non-numeric values. This property is used to indicate that a value is not a number. Number objects can be set to this value to indicate that they are not numeric values.


Numbers can be numbers or objects.

<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
var txt = typeof(x) + " " + typeof(y);
document.getElementById("demo").innerHTML=txt;
</script>

JavaScript String Object

String objects are used to process existing character blocks.


JavaScript string

String uses the length attribute length to calculate the length of a string

//String uses the length attribute length to calculate the length of a string
var txt="Hello World!";
document.write(txt.length);

//The string uses indexOf() to locate the first occurrence of a specified character in the string:
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
//If the corresponding character function is not found, return - 1


Content matching

The match() function is used to find a specific character in a string and, if found, returns that character.


replace content

The replace() method replaces some characters with others in a string.

str="Please visit Microsoft!"
var n=str.replace("Microsoft","w3cschool");

String case-to-case conversion

The string case conversion uses the function toUpperCase()/ toLowerCase():

var txt="Hello World!";       // String
var txt1=txt.toUpperCase();   // txt1 text will be converted to uppercase
var txt2=txt.toLowerCase();   // txt2 text will be converted to lowercase

Converting strings to arrays

<script>
function myFunction(){
	var str="a,b,c,d,e,f";
	var n=str.split(",");
	document.getElementById("demo").innerHTML=n[0];
}
</script>
//Output a


JavaScript Date (Date) object

Date objects are used to process dates and times.

getFullYear() Use getFullYear() to get the year.

getTime() getTime () returns the number of milliseconds from January 1, 1970 to the present.

<script>
function myFunction(){
	var d = new Date();
	var x = document.getElementById("demo");
	x.innerHTML=d.getTime();
}
</script>

setFullYear() How to use setFullYear() to set a specific date.

<script>
function myFunction(){
	var d = new Date();
	var x = document.getElementById("demo");
	x.innerHTML=d.getFullYear();
}
</script>

toUTCString() How to use toUTCString() to convert the date of the day (according to UTC) into a string.

<script>
function myFunction(){
	var d = new Date();
	var x = document.getElementById("demo");
	x.innerHTML=d.toUTCString();
}
</script>

getDay() How to use getDay() and arrays to display weeks, not just numbers.

<script>
function myFunction(){
	var d = new Date();
	var weekday=new Array(7);
	weekday[0]="Sunday";
	weekday[1]="Monday";
	weekday[2]="Tuesday";
	weekday[3]="Wednesday";
	weekday[4]="Thursday";
	weekday[5]="Friday";
	weekday[6]="Saturday";
	var x = document.getElementById("demo");
	x.innerHTML=weekday[d.getDay()];
}
</script>

Display a clock How to display a clock on a web page?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Rookie tutorial(runoob.com)</title>
<script>
function startTime(){
	var today=new Date();
	var h=today.getHours();
	var m=today.getMinutes();
	var s=today.getSeconds();// Add a'0'before the number less than 10
	m=checkTime(m);
	s=checkTime(s);
	document.getElementById('txt').innerHTML=h+":"+m+":"+s;
	t=setTimeout(function(){startTime()},500);
}
function checkTime(i){
	if (i<10){
		i="0" + i;
	}
	return i;
}
</script>
</head>
<body onload="startTime()">
	
<div id="txt"></div>
	
</body>
</html>

Date of creation

Date objects are used to process dates and times.  

Date objects can be defined by new keywords. The following code defines a date object named myDate

 

There are four ways to initialize the date:

new Date() // Current date and time
new Date(milliseconds) //Return to milliseconds from January 1, 1970 to the present
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

//Instance date
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)

Setting date
var myDate=new Date();
MyDate. setFullYear (2010, 0, 14); //14 January 2010

var myDate=new Date();
myDate.setDate(myDate.getDate()+5);//Set the date object to a date five days later

Comparison of two dates

var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();

if (x>today)
{
	alert("Today is before January 14, 2100");
}
else
{
	alert("Today is after January 14, 2100");
}

JavaScript Array (Array) Object

The function of an array object is to store a series of values with a separate variable name.


Create an array

//1: Conventional way:
var myCars=new Array(); 
myCars[0]="Saab";       
myCars[1]="Volvo";
myCars[2]="BMW";

//2: Concise way:
var myCars=new Array("Saab","Volvo","BMW");

//3::
var myCars=["Saab","Volvo","BMW"];

You can have different objects in an array

All JavaScript variables are objects. Array elements are objects. Functions are objects.

So you can have different variable types in the array.

You can include object elements, functions, arrays in an array:

myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;

Creating new methods

The prototype is the JavaScript global constructor. It can build properties and methods of new Javascript objects.

<script>
Array.prototype.myUcase=function(){
	for (i=0;i<this.length;i++){
		this[i]=this[i].toUpperCase();
	}
}
function myFunction(){
	var fruits = ["Banana", "Orange", "Apple", "Mango"];
	fruits.myUcase();
	var x=document.getElementById("demo");
	x.innerHTML=fruits;
}
</script>

//Click the button to output the array as a string.
<script>
function myFunction(){
	var fruits = ["Banana", "Orange", "Apple", "Mango"];
	var x=document.getElementById("demo");
	x.innerHTML=fruits.join();
}
</script>

//Click the button to reverse the sort of the array.
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction(){
	fruits.reverse();
	var x=document.getElementById("demo");
	x.innerHTML=fruits;
}
</script>

//Click the button to sort the array in ascending order.
<script>
function myFunction(){
	var points = [40,100,1,5,25,10];
	points.sort(function(a,b){return a-b});
	var x=document.getElementById("demo");
	x.innerHTML=points;
}
</script>

//Click the button to add elements to the array.
//result:Banana,Orange,Lemon,Kiwi,Apple,Mango
<script>
function myFunction(){
	var fruits = ["Banana", "Orange", "Apple", "Mango"];
	fruits.splice(2,0,"Lemon","Kiwi");
	var x=document.getElementById("demo");
	x.innerHTML=fruits;
}
</script>

JavaScript Math (arithmetic) object

Math (arithmetic) objects perform common arithmetic tasks.

round()//

Rounding the nearest integer to "2.5" is 3

<script>
function myFunction(){
	document.getElementById("demo").innerHTML=Math.round(2.5);
}
</script>

Click on the button to display a random number

Math.random();


// Click the button to return the maximum value between 5 and 10

document.getElementById("demo").innerHTML=Math.max(5,10);


Posted by Mark1inLA on Sat, 01 Jun 2019 11:41:09 -0700