JavaScript. Типы данных и операторы
- Литералы
- Переменные
- Массивы
- Функции
- Объекты
Они делятся на встроенные и пользовательские (определяемые программистом).
Литералы - данные, непосредственно используемые в программе. Литералы могут быть разных типов.
- Числовые литералы: 10 2.310 2.3е+2
- Строковый литерал: 'Строковый' "Строковый"
Литералы используются в операциях присваивания:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a=10; | |
var str='Строка' ; | |
if (x=='text') alert(x); |
Присваивание выполняется справа налево:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
result = x = 5+7; |
Экранирование кавычек в тексте знаком '/"'.
Переменные
Объявление переменных происходит через var, можно определять через запятую, присваивая ей значение или нет.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var k; | |
var h='Привет'; | |
var k, h='Привет'; | |
var t=37,a=3.2; |
Тип переменной определяется по её значению. JavaScript является гибко типизированным языком в разных частях программы одна и та же переменная может иметь значения разных типов.
Для определения типа переменой существует оператор typeof();
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var i=5; alert(typeof(i)) ; | |
i = new Array() ; alert(typeof(i)); | |
i=3.4; alert(typeof(i)); | |
i='Привет'; alert(typeof(i)); | |
i=window.open() ; alert(typeof(i)); |
Области видимости
Объявление с var вне функции делает переменную глобальной.
Объявление var внутри функции делает переменную локальной.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function f() | |
{ | |
var k=5; | |
} | |
f(); alert(k); |
Конфликт локальных и глобальных переменных
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var k=7; | |
function f() { | |
Var k=5; | |
} | |
Alert(k); |
Будет выдано 7, так как в блоке вывода фигурирует глобальная переменная.
Примечание, при объявлении можно var не писать.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for(i=0; i<8; i++) |
Отсутвие var в функции, делает переменную конструктора.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function f() | |
{ | |
Var i; //переменная локальная | |
k=5; //переменная глобальная | |
} |
Нестандартный пример с неожиданным выводом
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function f(i) { | |
k=7; | |
if(i==3) k=5; | |
else { | |
f(3); | |
alert(k) ; | |
} | |
} | |
f(0); |
Будет выведено 5, так как вызов f(3) изменил значение переменной k.
Массивы
Массивы делятся на встроенные, называемые коллекциями, и пользовательские.
Для определения пользовательского используется конструктор Array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = new Array(); //пустой массив длины 0 | |
h = new Array(10); //массив длины 10 | |
с = new Array(10, 'Привет'); //массив из двух элементов: числа и строки | |
d = [5, 'Тест', 2.71, 'Число е']; //краткий способ создавать массив из 4 элементов |
Элементы нумеруются с 0. Не могут быть многомерными. Но может быть массив массивов.
Методы по работе с массивами
Метод join() объединяет элементы массива в строку.
Обратный метод split() рабивает сроку на элементы массива по разделителю.
Пример
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
localURL= "file: ///C:/department/internet/js/2.html" | |
b=split(':/'); |
Полученный массив
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
b[0] = "file"; | |
b[1] = "//C"; | |
b[2] = "department/internet/js/2.html"; |
Меняем значения у 0 и 1 элементов массива:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
b[0] = "http:"; | |
b[1] = "/www.intuit.ru"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
globalURL = b.join("/"); // globalURL = http://www.intuit.ru/department/internet/js/2.html |
Метод reverse()
Метод reverse() применяется для изменения порядка элементов массива на противоположный. Инициализируем массив:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = new Array('мать', 'видит', 'дочь'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a[0] = 'дочь'; | |
a[1] = 'видит'; | |
a[2] = 'мать'; |
Метод sort()
Метод sort() интерпретирует элементы массива как строковые литералы и сортируем массив в алфавитном (лексикографическом) порядке. Метод sort() меняет массив. В предыдущем примере, применив a.sort, получим:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a[0] = 'видит'; | |
a[1] = 'дочь'; | |
a[2] = 'мать'; |
- у нее должно быть два аргумента
- она должна возвращать число
- если первый аргумент функции должен считаться меньшим (большим, равным), чем второй аргумент, то функция должна возвратить отрицательное (положительное, ноль) значение
Функция имеет вид:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a.sort(myfuction) |
Если нам необходимо сортировать числа, то мы можем использовать следующую функцию:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function compar(a,b) { | |
if(a < b) return -1; | |
if(a > b) return 1; | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.write("Алфавитный порядок: <br>"); | |
document.write(b.sort()); | |
document.write("<br> Алфавитный порядок: <br>"); | |
document.write(b.sort(compar)); |
Операторы
- {...}
- if ... else ...
- ()?
- while
- for
- break
- continue
- return
{...}
Фигурные скобки определяют составной оператор - блок.
Назначение - определение тела цикла, тело условного оператора или функции.
if ... else ...
Условный оператор применяется для ветвления программы по логическому условию. Есть два варианта синтаксиса:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (логическое_выражение) оператор; | |
if (логическое_выражение) оператор_1; else оператор_2; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (navigator.javaEnabled()) | |
alert('Ваш браузер поддерживает Java'); | |
else | |
alert('Ваш браузер НЕ поддерживает Java'); |
()?
Этот оператор называется условным выражением, выдает одно из двух значений в зависимости от выполнения некоторого условия. Синтаксис:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(логическое_выражение) ? значение_при_true : значение_при_false |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//1 пример | |
TheFinalMessage = (k<5) ? 'Готово!' : 'Подождите...'; | |
//2 пример | |
if (k<5) TheFinalMessage='Готово!'; | |
else TheFinalMessage='Подождите...'; |
while
Оператор while задает цикл. Определяется следующим образом:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
while (условие_продолжения_цикла) тело_цикла; |
- проверяется условие_продолжения цикла:
- если оно ложно (false), цикл закончен,
- если же оно истинно (true), продолжаем далее
- выполняем тело_цикла;
- переходим к п.1.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var s=''; | |
while (s.length < 6){ | |
s = prompt('Введите строку, длины не менее 6:', ''); | |
} | |
alert('Ваша строка' + s + '.Спасибо!'); |
for
Оператор for - оператор цикла. Он имеет вид:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for (инициализация_переменных_цикла; условие_продолжения_цикла; модификатор_переменных цикла) тело_цикла; |
- выполняется инициализация_переменных_цикла;
- проверяется условие_продолжения цикла:
- если оно ложно (false), цикл закончен,
- если же оно истинно (true), продолжаем далее
- выполняем тело_цикла;
- выполняется модификация_переменных_цикла
- переходим к п.1.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.write('Кубы чисел от 1 до 100:'); | |
for(n=1; n<=100; n++) | |
document.write('<BR>'+n+'<sup>3<\sup>=' + Math.pow(n,3)); |
break
Оператор break позволяет дострочно покинуть тело цикла. Изменим пример с кубами чисел, распечатаем только кубы, не превышающие 5000.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.write('Кубы чисел, меньше 5000:'); | |
for(n=1, n<=100, n++) { | |
s = Math.pow(n,3); | |
if (s>5000) break; | |
document.write('<BR>'+n+'<sup>3</sup>='+s); | |
} |
continiue
Оператор continue позволяет перейти к следующей итерации цикла, пропустив выполнение всех нижестоящих операторов в теле цикла.Если нам нужно вывести кубы чисел от 1 до 100, превышающие 10 000, то мы можем составить такой цикл:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.write('Кубы чисел, меньше 5000:'); | |
for(n=1, n<=100, n++) { | |
s = Math.pow(n,3); | |
if (s<=10000) continue; | |
document.write('<BR>'+n+'<sup>3</sup>='+s); | |
} |
return
Оператор return используют для возврата значения из функции или обработчика события.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sign(n){ | |
if (n>0) return 1; | |
if (n<0) return -1; | |
return 0; | |
} | |
alert(sign(-3)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<FORM ACTION="newpage.html" METHOD=post> | |
<INPUT TYPE=submit VALUE="Отправить?" onClick="alert("Не отправим!"); return false;"> | |
</FORM> |
Комментарии
Отправить комментарий