JavaScript basic concepts and basic syntax


1. Introduction

JavaScript is often referred to as js or js script

  • Concepts:
    1. Interpreted scripting language (code is not precompiled)
    2. Lightweight programming language
    3. Programming code that can be inserted into HTML pages
    (executed by all modern browsers after being inserted into HTML pages)

  • Function:
    Add dynamic functions to web pages
    to provide users with smoother and more beautiful browsing effects

Usually JavaScript scripts implement their functions by embedding them in HTML


2. Comments

Same as Java's single-line and multi-line comments

Single line comments: start with //

Multi-line comments: start with /* and end with */


3. Usage

There are three kinds

1. js in HTML page

Must be between script block tags

The position requirements are not strict (you can put head, body, and last, usually head or last)

Must be between script block tags

Code example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>js位置1</title>					
		<!--
			内部:js位置没有严格的要求
		-->
		<!--写在head-->
		<script>
			alert("hello script111!")
		</script>

	</head>
	<body>
		<!--写在body-->
		<script>
			alert("hello script222!")
		</script>
		
	</body>
</html>
	<!--写在最后-->
	<script>
		alert("hello script333!")
	</script>

2. External js

Scripts can be saved to external files. The file extension of external JavaScript files is .js

1. Write .js files externally

function fun1(){
    
    
	alert("这是js外部文件");
}

2. Introduce js files (either head or body)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>js位置2</title>			
		<!--
			外部:写在js文件中,外部文件不需要script标签
			引入外部script文件
			调用script文件
		-->
		<script type="text/javascript" src="../../js/myScript.js" ></script>
		<script>
			fun1();
		</script>	
			
	</head>
	
	<body>
	</body>
	
</html>

3. js in tag attributes

Directly written in some attributes of HTML tags for writing simple JavaScript code

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>js位置3</title>			
	</head>
	<body>
		<!--
			行内的js写法
		-->
		<a href="javascript:alert('行内的js写法')">行内的js写法</a>
		
	</body>
</html>

4. Display data

① window.alert() pop-up box

  • window can be omitted, which is equivalent to alert("displayed content");

② document.write() writes the content

  • document.write("displayed content")

③ innerHTML writing

  • document.getElementById("id value").innerHTML="Displayed content"
    Since loading is from top to bottom, the id value needs to be loaded first, so the script is placed at the bottom of the document

④ console.log is written to the browser console

  • console.log("displayed content")

Code example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>显示数据</title>
		<script>	
			/*
			1、使用windows弹出框,弹出数据,两种写法都可以
			*/
			alert("hello")
			window.alert("hello again")

			/*
			2、使用document,显示数据
			 */
			document.write("hello document")

			/*
			 3、使用innerHTML写入
			 加载从上往下,因此先获取div1,此时div1还未加载,因此将script放在文档最下面
			 */
			//document.getElementById("div1").innerHTML="hello innerHTML"
			/*
			 4、使用console.log写入到浏览器控制台
			 */
			console.log("hello log")
		</script>
	</head>
	<body>
		<div id = "div1">			
		</div>
	</body>
</html>

<!--
3、使用innerHTML写入
加载从上往下,因此先获取div1,此时div1还未加载,因此将script放在文档最下面
-->
<script>
	document.getElementById("div1").innerHTML="hello innerHTML!"
</script>



5. Basic Grammar

JavaScript is a scripting language. The browser executes the script code line by line when reading the code (the js statement sends commands to the browser to tell the browser what to do)

  • Tips:
    Generally, only write one statement per line, and write a semicolon at the end of each sentence.

5.1 Variables

5.1.1 Basic syntax

Keywords: var

Uniformly use var for variable declaration, and the data type of the variable is determined based on the assignment.

  • Declare variables:
    var variable name;

  • Naming rules:
    1. Variables must start with a letter
    2. Variables can also start with $ and _ symbols
    3. Variable names are case-sensitive (y and Y are different variables)
    4. Keyword reserved words cannot be used

  • Naming convention:
    1. Know the meaning when you see the name, and name it according to the meaning of the variable.
    2. Camel case naming, the first letter of the first word is lowercase, and the first letter of each subsequent word is capitalized.

Code example:

var myCompany; //声明变量
myCompany='alibaba'; //赋值

var x=5;//声明的同时赋值
var y=6;

var z=x+y;//变量也可以存储表达式

5.1.2 Scope

  • Local variables
    are variables declared inside a function and can only be used inside the function.
  • Global variables
    are variables declared outside the function and can be accessed by all scripts and functions.
5.1.3 Life cycle

The lifetime of a variable begins when it is declared

Local variables will be deleted after the function is run, and global variables will be deleted after the page is closed.


5.2 Data types

5.2.1 Basic data types

String

variable to store characters

Strings must use single or double quotes

  • Tips:
    In nesting, single quotes are nested in double quotes or double quotes are nested in single quotes.

Code example:

var myCompany="alibaba";

//引号嵌套,单引号嵌套双引号or双引号嵌套单引号
var demo1='字符串中嵌套"字符串"。';
var demo2="字符串中嵌套'字符串'。";

NumberNumber

There is only one numeric type that can represent both floating point numbers and integers

Code example:

var intValue=11;
var floatValue=11.1;

//极大或极小的数字可以通过科学计数法来书写:
var demo1=666e5; //66600000
var demo2=-666e-5; //-0.00666

Boolean

true or false

Code example:

var f1=true;
var f2=false;

Null

Indicates that the value is empty

Clear the variable by setting its value to null

var isNULL=null;
UndefinedUndefined

Indicates that the variable does not contain a value

There are 4 situations in which undefined will appear

① Variable declaration without assignment

var obj;
alert(obj);//obj值为undefined

② Get attributes that do not exist in the object

var obj;
alert(obj.name);//报错信息: "Uncaught TypeError: Cannot read property 'name' of
undefined"

③ The function requires actual parameters, but no value is passed when calling

At this time the formal parameter is undefined

④ The function call does not return a value or there is no data after return.

At this time, the variable returned by the receiving function is undefined.

Code example:

function printNum(num){
    
    
	alert(num);
}
var result=printNum();//调用函数未传递参数,执行函数的时候num的值是undefined
alert(result);//result的值也是undefined,因为printNum()没有返回值

Symbol

Represents a unique value


5.2.2 Reference data types

ObjectObject
ArrayArray
Function

5.2.3 Dynamic typing (deprecated)

Dynamic typing, i.e. the same variable can be used as different types

Code example:

var param; // param类型为 undefined
param = 5; // param 为数字
param = "alibaba"; // param 为字符串

5.3 Operators

  • Arithmetic operators
    +, -, *, /, %, ++, - -
  • Assignment operators
    =, +=, -=, *=, /=, %=
  • String concatenation character
    +
  • Logical operators
    &&, ||, !
  • Conditional operator
    ? :
  • Comparison operators
    ==, !=, >, <, >=, <=
    ===: Absolute equality (both values ​​and types are equal)
    !==: Not absolute equality (one or two of the values ​​and types are not equal) are not equal)

Code example:

var x=5;
var f=(x===5); // true
f=(x==='5');// false
f=(x!==5); // false
f=(x!=='5');// true

5.4 Objects

5.4.1 Common objects

String

.length can get the length of a string (length is an attribute, not a method, so there is no need to add () when calling)

The length of the transfer symbol counts as one, that is, the length of \' is 1

method:

method describe
charAt() Returns the character at the specified position
charCodeAt() Returns the Unicode encoding of the character at the specified position
concat() Concatenates two or more strings and returns a new string
fromCharCode() Convert Unicode encoding to characters
indexOf() Returns the first occurrence of a specified string value in a string
includes() Finds whether a string contains a specified substring
lastIndexOf() Search the string from back to front, and return the last occurrence of the string starting from the starting position (0)
match() Find finds a match of one or more regular expressions
repeat() Copies a string a specified number of times and concatenates them together and returns
replace() Find matching substrings in a string and replace substrings that match a regular expression
search() Find values ​​matching a regular expression
slice() Extracts a fragment of a string and returns the extracted part in a new string
split() Split string into string array
startsWith() Check whether a string starts with a specified substring
substr() Extracts a specified number of characters from a string from the starting index number
substring() Extract characters between two specified index numbers in a string
toLowerCase() Convert string to lowercase
toUpperCase() Convert string to uppercase
trim() Remove whitespace from both sides of string
toLocaleLowerCase() Convert a string to lowercase according to the local host's locale
toLocaleUpperCase() Convert a string to uppercase based on the local host's locale
valueOf() Returns the original value of a string object
toString() Return a string

Array

Array, used to store multiple values ​​in a variable

.length can get the length of the array

Three ways:

	//方法一
	var letters = new Array();
	for(var i = 0; i < 4; i++) {
    
    
		letters[i] = "letter" + i;
	}
	for(var i = 0; i < letters.length; i++) {
    
    
		document.write(letters[i] + "<br/>");
	}
	
	//方法二	
	var numbers = [1,2,3,4,5];
	for(var i = 0; i < numbers.length; i++) {
    
    
		document.write(numbers[i] + "<br/>");
	}
	
	//方法三	
	var classes = new Array("class1","class2","class3");
	for(var i = 0; i < classes.length; i++) {
    
    
		document.write(classes[i] + "<br/>");
	}

method:

method describe
concat() Concatenates two or more arrays and returns the result
copyWithin() Copies an element from a specified position in an array to another specified position in an array
entries() Returns an iterable object of an array
every() Check whether each element of numeric elements meets the condition
fill() Fill an array with a fixed value
filter() Detect numeric elements and return an array of all elements that meet the criteria
find() Returns array elements that match the conditions passed into the test (function)
findIndex() Returns the index of the array element that meets the criteria passed into the test (function)
forEach() The callback function is executed once for each element of the array
from() Create an array from the given objects
includes() Determine whether an array contains a specified value
indexOf() Searches for an element in an array and returns its position
isArray() Determine whether the object is an array
join() Put all elements of an array into a string
keys() Returns an iterable object of the array containing the keys of the original array
lastIndexOf() Searches for an element in an array and returns its last occurrence
map() Process each element of the array through the specified function and return the processed array
pop() Removes the last element of an array and returns the removed element
push() Adds one or more elements to the end of an array and returns the new length
reduce() Count array elements into a value (left to right)
reduceRight() Count array elements into a value (right to left)
reverse() Reverse the order of elements of an array
shift() Removes and returns the first element of an array
slice() Selects a portion of an array and returns a new array
some() Check whether any element in the array meets the specified condition
sort() Sort the elements of an array
splice() Add or remove elements from an array
toString() Convert an array to a string and return the result
unshift() Adds one or more elements to the beginning of an array and returns the new length
valueOf() Returns the original value of the array object

Date

Create date object:

//返回当前日期
var date1 = new Date();

//milliseconds:1970-1-1~现在的毫秒数
var date2 = new Date(milliseconds);

//符合日期类型的字符串(年月日-时分秒)
var date3 = new Date(dateString);

//月份取值为0~11,周日~周六取值为0~6
var date4 = new Date(year, month, day, hours, minutes, seconds, milliseconds);

Commonly used methods:

method describe
getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)。
getDay() 从 Date 对象返回一周中的某一天 (0 ~ 6)。
getFullYear() 从 Date 对象以四位数字返回年份。
getHours() 返回 Date 对象的小时 (0 ~ 23)。
getMinutes() 返回 Date 对象的分钟 (0 ~ 59)。
getMonth() 从 Date 对象返回月份 (0 ~ 11)。
getSeconds() 返回 Date 对象的秒数 (0 ~ 59)。
setDate() 设置 Date 对象中月的某一天 (1 ~ 31)。
setFullYear() 设置 Date 对象中的年份(四位数字)。
setHours() 设置 Date 对象中的小时 (0 ~ 23)。
setMinutes() 设置 Date 对象中的分钟 (0 ~ 59)。
setMonth() 设置 Date 对象中月份 (0 ~ 11)。
setSeconds() 设置 Date 对象中的秒钟 (0 ~ 59)。

其他方法:

方法 描述
getMilliseconds() 返回 Date 对象的毫秒(0 ~ 999)。
getTime() 返回 1970 年 1 月 1 日至今的毫秒数。
getTimezoneOffset() 返回本地时间与格林威治标准时间 (GMT) 的分钟差。
getUTCDate() 根据世界时从 Date 对象返回月中的一天 (1 ~ 31)。
getUTCDay() 根据世界时从 Date 对象返回周中的一天 (0 ~ 6)。
getUTCFullYear() 根据世界时从 Date 对象返回四位数的年份。
getUTCHours() 根据世界时返回 Date 对象的小时 (0 ~ 23)。
getUTCMilliseconds() 根据世界时返回 Date 对象的毫秒(0 ~ 999)。
getUTCMinutes() 根据世界时返回 Date 对象的分钟 (0 ~ 59)。
getUTCMonth() 根据世界时从 Date 对象返回月份 (0 ~ 11)。
getUTCSeconds() 根据世界时返回 Date 对象的秒钟 (0 ~ 59)。
getYear() 已废弃。 请使用 getFullYear() 方法代替。
parse() 返回1970年1月1日午夜到指定日期(字符串)的毫秒数。
setMilliseconds() 设置 Date 对象中的毫秒 (0 ~ 999)。
setTime() setTime() 方法以毫秒设置 Date 对象。
setUTCDate() 根据世界时设置 Date 对象中月份的一天 (1 ~ 31)。
setUTCFullYear() 根据世界时设置 Date 对象中的年份(四位数字)。
setUTCHours() 根据世界时设置 Date 对象中的小时 (0 ~ 23)。
setUTCMilliseconds() 根据世界时设置 Date 对象中的毫秒 (0 ~ 999)。
setUTCMinutes() 根据世界时设置 Date 对象中的分钟 (0 ~ 59)。
setUTCMonth() 根据世界时设置 Date 对象中的月份 (0 ~ 11)。
setUTCSeconds() setUTCSeconds() 方法用于根据世界时 (UTC) 设置指定时间的秒字段。
setYear() 已废弃。请使用 setFullYear() 方法代替。
toDateString() 把 Date 对象的日期部分转换为字符串。
toGMTString() 已废弃。请使用 toUTCString() 方法代替。
toISOString() 使用 ISO 标准返回字符串的日期格式。
toJSON() 以 JSON 数据格式返回日期字符串。
toLocaleDateString() 根据本地时间格式,把 Date 对象的日期部分转换为字符串。
toLocaleTimeString() 根据本地时间格式,把 Date 对象的时间部分转换为字符串。
toLocaleString() 根据本地时间格式,把 Date 对象转换为字符串。
toString() 把 Date 对象转换为字符串。
toTimeString() 把 Date 对象的时间部分转换为字符串。
toUTCString() 根据世界时,把 Date 对象转换为字符串。实例: var today = new Date(); var UTCstring = today.toUTCString();
UTC() 根据世界时返回 1970 年 1 月 1 日 到指定日期的毫秒数。
valueOf() 返回 Date 对象的原始值。

Math

属性:

属性 描述
E 返回算术常量 e,即自然对数的底数(约等于2.718)
LN2 返回 2 的自然对数(约等于0.693)
LN10 返回 10 的自然对数(约等于2.302)
LOG2E 返回以 2 为底的 e 的对数(约等于 1.4426950408889634)
LOG10E 返回以 10 为底的 e 的对数(约等于0.434)
PI 返回圆周率(约等于3.14159)
SQRT1_2 返回 2 的平方根的倒数(约等于 0.707)
SQRT2 返回 2 的平方根(约等于 1.414)

常用方法:

方法 描述
ceil(x) 对数进行上舍入
floor(x) 对 x 进行下舍入
round(x) 四舍五入
pow(x,y) 返回 x 的 y 次幂
max(x,y,z,…,n) 返回 x,y,z,…,n 中的最高值
min(x,y,z,…,n) 返回 x,y,z,…,n中的最低值
random() 返回 0 ~ 1 之间的随机数

其他方法:

方法 描述
abs(x) 返回 x 的绝对值
acos(x) 返回 x 的反余弦值
asin(x) 返回 x 的反正弦值
atan(x) 以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值
atan2(y,x) 返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间)
cos(x) 返回数的余弦
exp(x) 返回 Ex 的指数
log(x) 返回数的自然对数(底为e)
sin(x) 返回数的正弦
sqrt(x) 返回数的平方根
tan(x) 返回角的正切

5.4.2 自定义对象

对象是变量的容器,里面可以定义多个变量

定义
  • 定义属性:
    变量以键值对形式进行存储(name : value)
    不同属性以逗号分隔,可换行可不换行

  • 定义方法:
    方法名称后面直接跟function

代码示例:

var people = {
    
    name:"SelcouthAI",age:20,codeYear:"1年"};
			
var student = {
    
    
	name:"SelcouthAI",	
	age:20,
	//方法后面直接跟function
	job:function(){
    
    
		alert("正在被包工头支配的新生代农民工");
	}			
}

调用
  • 调用属性
    第一种方式:类名.属性名
    第二种方式:类名[“属性名”]

  • 调用方法
    类名.方法

代码示例:

var name = people.name;
document.write("name:"+name);
			
var age = people["age"];
document.write("age:"+age);
			
student.job();

5.5 函数

5.5.1 常用全局函数

isNaN(param)
  • tips:
    全局属性NaN:非数值(Not a Number)

用于检查其参数是否是非数字值,不是数值返回true

代码示例:

console.log(isNaN(666));//false
console.log(isNaN(6+66));//false
console.log(isNaN("hello"));//true

parseFloat(String)

解析字符串,并返回一个浮点数

  • tips:
    只返回字符串中第一个数字,开头和结尾允许空格
    如果字符串的第一个非空字符不能被转换为数字,则返回 NaN

代码示例:

console.log(parseFloat("66"));//66
console.log(parseFloat("666.66"));//666.66
console.log(parseFloat("1024 2048 4096"));//1024
console.log(parseFloat(" 666 "));//666
console.log(parseFloat("1年"));//1
console.log(parseFloat("码龄1年"));//NaN

parseInt(string,radix)

解析一个字符串,返回整数

string :必要参数,被解析的字符串
radix :表示要解析的数字的基数( 2 ~ 36 )

  • 当参数 radix 的值为 0或没有设置参数时,根据 string 来判断数字的基数:
    “0x” 开头,其余部分解析为十六进制的整数
    以 0 开头,其余部分解析为八进制或十六进制的数字
    以 1 ~ 9 开头,解析为十进制的整数

  • tips:
    只返回字符串中第一个数字,开头和结尾允许空格
    如果字符串的第一个非空字符不能被转换为数字,则返回 NaN

代码示例:

console.log(parseInt("66"));//66
console.log(parseInt("666.6"));//666.6
console.log(parseInt("1024 2048 4096"));//1024
console.log(parseInt("1年"));//1
console.log(parseInt("码龄1年"));//NaN

console.log(parseInt("10",10));//10
console.log(parseInt("010"));//10
console.log(parseInt("10",8));//8
console.log(parseInt("0x10"));//16
console.log(parseInt("10",16));//16

5.5.2 自定义函数

关键字:function

  • tips:
    不需要声明类型,直接写参数名称
    函数是否有返回值取决于函数体中是否有return关键字
    返回值的类型取决于return中内容的类型
function 自定义函数名称(参数列表){
    
    
	...
}

代码示例:

	//无参无返回值的函数
	function print(){
    
    
		document.write("无参无返回值的函数");
	}
	print();
	
	//有参无返回值的函数
	function print1(num){
    
    
		document.write("有参无返回值的函数,参数为" + num);
	}
	print1(666);
	
	//有参有返回值的函数
	function print2(a,b){
    
    
		document.write("有参有返回值的函数,参数分别为"+a+"和"+b);
		return a+b;
	}
	var sum = print2(1,6);

5.5.3 匿名函数

把函数赋给一个变量,再调用变量

代码示例:

	//无参无返回值的函数
	var fun = function(){
    
    
		document.write("无参无返回值的函数");
	}
	fun();
	
	//有参无返回值的函数
	var fun1 = function(num){
    
    
		document.write("有参无返回值的函数,参数为" + num);
	}
	fun1(6);
	
	//有参有返回值的函数
	var fun2 = function(a,b){
    
    
		document.write("有参有返回值的函数,参数分别为"+a+"和"+b);
		return a+b;
	}
	var sum = fun2(1,6);
	alert(sum);

Guess you like

Origin blog.csdn.net/m0_50609545/article/details/119938123