3. Getting started with JavaScript functions

JS function beginners
The role of the function:
through the function can encapsulate any number of statements, and can be called and executed at any place, any time.

Function definition:
through function declaration, followed by a set of parameters and function body:
Insert picture description here

function myFun(){
    
    
	alert('hello world');
}
myFun();

function myFun2(num1,num2){
    
    
	var sum=num1+num2;
	alert(num1+'和'+num2+'相加的结果是'+sum);
	
}
myFun2(3,5);

Although it can be called repeatedly, but always alert, the browser also wants to prohibit you from popping up.

At this time, the return value of the function appears.
Any function implements the return value through the return statement followed by the return value.

function myFun2(num1,num2){
    
    
	var sum=num1+num2;
	return (num1+'和'+num2+'相加的结果是'+sum);
	
}
document.write(myFun2(3,5));
alert(myFun2(3,55));
console.log(myFun2(4,5));

Insert picture description here

function my(arg){
    
    
	if(isNaN(arg)) return;
	return arg*2;
}
console.log(my("cbd"));
console.log(my("232"));

Master the parameters in the function
Insert picture description here

function inner(num1,num2){
    
    
	console.log(num2);  //undefined
}
inner(10);
function inner(){
    
    
	console.log(arguments.length);//2
	console.log(arguments[0]);//索引从0开始的正整数
}
inner(10,5);

function inner2(){
    
    
	arguments[0]=99;
	console.log(arguments[0]);//索引从0开始的正整数
}
inner2(10,5);
//但在严格模式下,即使修改也是原来的值

Find the average of any set of numbers

function inner3(){
    
    
	var sum=0,
		len=arguments.length,
		i;
	for(i=0;i<len;i++){
    
    
		//console.log(arguments[i]);
		sum+=arguments[i];
	}
	return sum/len;
}
var avg=inner3(10,5,555,656);
console.log(avg);

Arguments are objects, not arrays, but have some types with arrays.

In js, some objects provide commonly used attributes and methods, these are called built-in objects.

NEXT:
commonly used arrays, strings, Date, Math built-in objects.

Guess you like

Origin blog.csdn.net/qq_44682019/article/details/108893739