русс | укр

Языки программирования

ПаскальСиАссемблерJavaMatlabPhpHtmlJavaScriptCSSC#DelphiТурбо Пролог

Компьютерные сетиСистемное программное обеспечениеИнформационные технологииПрограммирование

Все о программировании


Linux Unix Алгоритмические языки Аналоговые и гибридные вычислительные устройства Архитектура микроконтроллеров Введение в разработку распределенных информационных систем Введение в численные методы Дискретная математика Информационное обслуживание пользователей Информация и моделирование в управлении производством Компьютерная графика Математическое и компьютерное моделирование Моделирование Нейрокомпьютеры Проектирование программ диагностики компьютерных систем и сетей Проектирование системных программ Системы счисления Теория статистики Теория оптимизации Уроки AutoCAD 3D Уроки базы данных Access Уроки Orcad Цифровые автоматы Шпаргалки по компьютеру Шпаргалки по программированию Экспертные системы Элементы теории информации

Objects


Дата добавления: 2015-07-09; просмотров: 531; Нарушение авторских прав


JavaScript has very nice notational[e32] conveniences[e33] for manipulating hashtables.

var myHashtable = {};

This statement[e34] makes a new hashtable and assigns it to a new local variable. JavaScript is loosely typed[e35] , so we don't use type names in declarations. We use subscript[e36] notation to add, replace, or retrieve elements in the hashtable.

myHashtable["name"] = "Carl Hollywood";

There is also a dot notation which is a little more convenient[e37] .

myHashtable.city = "Anytown";

The dot notation can be used when the subscript is a string constant in the form of a legal identifier[e38] . Because of an error in the language definition[e39] , reserved[e40] words cannot be used in the dot notation, but they can be used in the subscript notation.

You can see that JavaScript's hashtable notation is very similar to Java's object and array notations. JavaScript takes this much farther[e41] : objects and hashtables are the same thing, so I could have written

var myHashtable = new Object();

and the result would have been exactly the same.

There is an enumeration[e42] capability [e43] built into the for statement.

for (var n in myHashtable) {

if (myHashtable.hasOwnProperty(n)) {

document.writeln("<p>" + n + ": " + myHashtable[n] + "</p>");

}

}

The result will be

<p>name: Carl Hollywood</p>

<p>city: Anytown</p>

An object is a container of name/value pairs. The names are strings (or other elements such as numbers that are converted to strings). The values can be any of the data types, including other objects. Objects are usually implemented[e44] as hash-tables, but none of the hash-table nature (such as hash functions or rehashing[e45] methods) is visible.



Objects can easily be nested[e46] inside of other objects, and expressions can reach into the inner[e47] objects.

this.div = document.body.children[document.body.children.length - 1];

In the object literal notation, an object description is a set of comma-separated name/value pairs inside curly braces[e48] . The names can be identifiers or strings followed by a colon[e49] . Because of an error in the language definition, reserved words cannot be used in the identifier form, but they can be used in the string form. The values can be literals or expressions of any type.

var myObject = {name: "Jack B. Nimble", 'goto': 'Jail', grade: 'A', level: 3};

return {

event: event,

op: event.type,

to: event.srcElement,

x: event.clientX + document.body.scrollLeft,

y: event.clientY + document.body.scrollTop};

emptyObject = {};

JavaScript's object literals are the basis of the JSON data interchange format.

New members can be added to any object at any time by assignment[e50] .

myObject.nickname = 'Jackie the Bee';

Arrays and functions are implemented[e51] as objects.

Arrays

Arrays in JavaScript are also hashtable objects. This makes them very well suited to sparse[e52] array applications. When you construct an array, you do not need to declare a size. Arrays grow automatically, much like Java vectors. The values are located by a key, not by an offset[e53] . This makes JavaScript arrays very convenient to use, but not well suited for applications in numerical analysis.

The main difference between objects and arrays is the length property. The length property is always 1 larger than the largest integer key in the array. There are two ways to make a new array:

var myArray = [];

var myArray = new Array();

Arrays are not typed. They can contain numbers, strings, booleans, objects, functions, and arrays.You can mix strings and numbers and objects in the same array. You can use arrays as general nested sequences[e54] , much as s-expressions. The first index in an array is usually zero.

When a new item is added to an array and the subscript is an integer that is larger than the current[e55] value of length, then the length is changed to the subscript plus one. This is a convenience feature that makes it easy to use a for loop to go through the elements of an array.

Arrays have a literal notation, similar to that for objects.

myList = ['oats', 'peas', 'beans', 'barley'];

 

emptyArray = [];

 

month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

 

slides = [

{url: 'slide0001.html', title: 'Looking Ahead'},

{url: 'slide0008.html', title: 'Forecast'},

{url: 'slide0021.html', title: 'Summary'}

];

A new item can be added to an array by assignment.

a[i + j] = f(a[i], a[j]);



<== предыдущая лекция | следующая лекция ==>
Data Types | Prototype


Карта сайта Карта сайта укр


Уроки php mysql Программирование

Онлайн система счисления Калькулятор онлайн обычный Инженерный калькулятор онлайн Замена русских букв на английские для вебмастеров Замена русских букв на английские

Аппаратное и программное обеспечение Графика и компьютерная сфера Интегрированная геоинформационная система Интернет Компьютер Комплектующие компьютера Лекции Методы и средства измерений неэлектрических величин Обслуживание компьютерных и периферийных устройств Операционные системы Параллельное программирование Проектирование электронных средств Периферийные устройства Полезные ресурсы для программистов Программы для программистов Статьи для программистов Cтруктура и организация данных


 


Не нашли то, что искали? Google вам в помощь!

 
 

© life-prog.ru При использовании материалов прямая ссылка на сайт обязательна.

Генерация страницы за: 0.179 сек.