Функции
Определим простейшую функцию:
function display(){
document.write("функция в JavaScript");
}
Можно использовать анонимные функции:
var display = function(){ // определение функции
document.write("анонимная функция в JavaScript");
}
display();
Также мы можем динамически присваивать функции для переменной:
function goodMorning(){
document.write("Доброе утро");
}
function goodEvening(){
document.write("Добрый вечер");
}
var message = goodMorning;
message(); // Доброе утро
message = goodEvening;
message(); // Добрый вечер
Рассмотрим передачу параметров:
function display3(x){ // определение функции
var z = x * x;
document.write(x + " в квадрате равно " + z);
}
display(5); // вызов функции
С помощью spread-оператора ... мы можем передать набор значений для этих параметров из массива:
function sum(a, b, c){
let d = a + b + c;
document.write(d);
}
document.write("<br><p> Значение переданные в функцию напрямую:<p/><br>")
sum(1, 2, 3);
var nums = [4, 5, 6];
document.write("<br><p> Значение переданные в функцию из массива:<p/><br>")
sum(...nums);
Параметры по умолчанию:
function display(x, y){
if(y === undefined) y = 5;
if(x === undefined) x = 8;
let z = x * y;
console.log(z);
}
display(); // 40
display(6); // 30
display(6, 4) // 24
Параметры по умолчанию:
function display(x = 5, y = 10){
let z = x * y;
console.log(z);
}
display(); // 50
display(6); // 60
display(6, 4) // 24
При необходимости мы можем получить все переданные параметры через глобально доступный массив arguments:
function display(){
var z = 1;
for(var i=0; i<arguments.length; i++)
z *= arguments[i];
console.log(z);
}
display(6); // 6
display(6, 4) // 24
display(6, 4, 5) // 120
переменное количество значений:
function display(season, ...temps){
document.write(season);
for(index in temps){
document.write(temps[index]);
}
}
display("Весна", -2, -3, 4, 2, 5);
display("Лето", 20, 23, 31);
Функция может возвращать результат. Для этого используется оператор return:
var y = 5;
var z = square(y);
document.write(y + " в квадрате равно " + z);
function square(x) {
return x * x;
}
Функции могут выступать в качестве параметров других функций:
function sum(x, y){
return x + y;
}
function subtract(x, y){
return x - y;
}
function operation(x, y, func){
var result = func(x, y);
console.log(result);
}
console.log("Sum");
operation(10, 6, sum); // 16
console.log("Subtract");
operation(10, 6, subtract); // 4
Одна функция может возвращать другую функцию:
function menu(n){
if(n==1) return function(x, y){ return x+y;}
else if(n==2) return function(x, y){ return x - y;}
else if(n==3) return function(x, y){ return x * y;}
return undefined;
}
for(var i=1; i < 5; i++){
var action = menu(i);
if(action!==undefined){
var result = action(5, 4);
console.log(result);
}
}