Javascript - Colecciones con índice


Colecciones con índice


Este cápitulo presenta las colecciones de datos que son ordenadas por un valor índice. Esto incluye arrays y construcciónes "array-like" tales como objetos Array y objetos TypedArray .

Objetos Matriz o ArraySección

Una  matriz o array es un conjunto ordenado de valores al que se refiere con un nombre y un índice. Por ejemplo: podría tener un array llamado  emp que contenga a los nombre de los empleados indexados por su número de empleado. Así  emp[1] sería el empleado número uno , emp[2] seria el empleado número dos, y así sucesivamente.
JavaScript no tiene un tipo de dato de matriz explícito. Sin embargo, podemos utilizar el objeto Array predefinido y sus métodos para trabajar con matrices en sus aplicaciones. El objeto Array tiene métodos para manipular matrices de varias maneras, tales como unirlas, invertirlas, y ordenarlas. Tiene una propiedad para determinar la longitud de la matriz y otras propiedades para su uso con expresiones regulares.

Creando una matriz o arraySección

Las siguientes declaraciones crean matrices equivalentes :
var arr = new Array(element0, element1, ..., elementN);
var arr = Array(element0, element1, ..., elementN);
var arr = [element0, element1, ..., elementN];
element0, element1, ..., elementN es una lista de valores para los elementos de la matriz. Cuando se especifican estos valores , la matriz se inicializa con ellos como elementos de la matriz. La propiedad de length de la matriz se establece con el número de argumentos. 
Los corchetes en la sintaxis estan llamando a  "literal de la matriz" o "inicializador de matriz".  Siendo este más corto que otras formas de creación de la matriz, y así se prefiere generalmente. Vea Array literals para más detalles. Vea literales de conjunto para obtener más detalles.
Para crear una matriz con longitud distinta de cero, pero sin ningún elemento, se puede utilizar cualquiera de las siguientes opciones:
var arr = new Array(arrayLength);
var arr = Array(arrayLength);

// Esto tiene exactamente el mismo efecto
var arr = [];
arr.length = arrayLength;
Nota: en el código de arriba, arrayLength debe ser Number. De otra forma, se creará un array con un único valor (el que fué provisto). Llamar arr.length devolverá arrayLength, pero el array realmente contendrá elementos vacíos (undefined). Correr un bucle for...in en el array no devolverá ninguno de sus elementos.
Adicionalmente a la nueva variable definida como se muestra arriba, los arrays también pueden ser asignados como una propiedad de un objeto nuevo o ya existente:
var obj = {};
// ...
obj.prop = [element0, element1, ..., elementN];

// OR
var obj = {prop: [element0, element1, ...., elementN]}
Si deseas inicializar un array con un solo elemento, y este debe ser un valor de tipo Number, deberás utilizar la sintaxis de corchetes, Cuando se pasa solo un valor Number al constructor o función Array(), este es interpretado como la longitud del array (arrayLength), no como un solo elemento. 
var arr = [42];
var arr = Array(42); // Crea un array sin elementos, 
                     // pero con una arr.length de 42

// El código de arriba es equivalente a lo siguiente
var arr = [];
arr.length = 42;
Llamar Array(N) resulta en un error RangeError, si N es un entero con una parte fraccionaria distinta de 0. El siguiente ejemplo ilustra este comportamiento.
var arr = Array(9.3);  // RangeError: Longitud de array inválida
Si tu código necesita crear arrays con elementos únicos de tipos arbitrarios, es más seguro utilizar literales de array. O, crear un array vacío antes que agregar un único elemento a el.

LLenando un arraySección

Puedes llenar un array al asignar valores a sus elementos. Por ejemplo,
var emp = [];
emp[0] = "Casey Jones";
emp[1] = "Phil Lesh";
emp[2] = "August West";
Nota:  si en el código de arriba utilizas un valor no entero en el operador del array, se creará una propiedad en el objeto que representa el array, y no un elemento del array.
var arr = [];
arr[3.4] = "Oranges";
console.log(arr.length);                // 0
console.log(arr.hasOwnProperty(3.4));   // true
También puedes llenar un array al crearlo:
var myArray = new Array("Hello", myVar, 3.14159);
var myArray = ["Mango", "Apple", "Orange"]

Hacer referencia a elementos de un arraySección

Puedes hacer referencia a los elementos contenidos en un array, usando el número ordinal del elemento. Por ejemplo, supongamos que defines el siguiente array:
var myArray = ["Wind", "Rain", "Fire"];
Ahora puedes hacer referencia el primer elemento del array conmyArray[0] y al segundo elemento de array con myArray[1]. Los indices de elemento comienzan siempre por cero.
Nota: the array operator (square brackets) is also used for accessing the array's properties (arrays are also objects in JavaScript). For example,
var arr = ["one", "two", "three"];
arr[2];  // three
arr["length"];  // 3

Understanding lengthSección

At the implementation level, JavaScript's arrays actually store their elements as standard object properties, using the array index as the property name. The length property is special; it always returns the index of the last element plus one (in following example Dusty is indexed at 30 so cats.length returns 30 + 1). Remember, JavaScript Array indexes are 0-based: they start at 0, not 1. This means that the length property will be one more than the highest index stored in the array:
var cats = [];
cats[30] = ['Dusty'];
console.log(cats.length); // 31
You can also assign to the length property. Writing a value that is shorter than the number of stored items truncates the array; writing 0 empties it entirely:
var cats = ['Dusty', 'Misty', 'Twiggy'];
console.log(cats.length); // 3

cats.length = 2;
console.log(cats); // logs "Dusty,Misty" - Twiggy has been removed

cats.length = 0;
console.log(cats); // logs nothing; the cats array is empty

cats.length = 3;
console.log(cats); // [undefined, undefined, undefined]

Iterando sobre arraysSección

Una operación común es iterar sobre los valores de un array, procesando cada uno de ellos de alguna manera. La forma más sencilla de hacerlo es la siguiente:
var colors = ['red', 'green', 'blue'];
for (var i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}
If you know that none of the elements in your array evaluate to false in a boolean context — if your array consists only of DOM nodes, for example, you can use a more efficient idiom:
var divs = document.getElementsByTagName('div');
for (var i = 0, div; div = divs[i]; i++) {
  /* Process div in some way */
}
This avoids the overhead of checking the length of the array, and ensures that the div variable is reassigned to the current item each time around the loop for added convenience.
The forEach() method provides another way of iterating over an array:
var colors = ['red', 'green', 'blue'];
colors.forEach(function(color) {
  console.log(color);
});
The function passed to forEach is executed once for every item in the array, with the array item passed as the argument to the function. Unassigned values are not iterated in a forEachloop.
Note that the elements of array omitted when the array is defined are not listed when iterating by forEach,but are listed when undefined has been manually assigned to the element:
var array = ['first', 'second', , 'fourth'];

// returns ['first', 'second', 'fourth'];
array.forEach(function(element) {
  console.log(element);
})

if(array[2] === undefined) { console.log('array[2] is undefined'); } // true

var array = ['first', 'second', undefined, 'fourth'];

// returns ['first', 'second', undefined, 'fourth'];
array.forEach(function(element) {
  console.log(element);
})
Since JavaScript elements are saved as standard object properties, it is not advisable to iterate through JavaScript arrays using for...in loops because normal elements and all enumerable properties will be listed.

Array methodsSección

The Array object has the following methods:
concat() joins two arrays and returns a new array.
var myArray = new Array("1", "2", "3");
myArray = myArray.concat("a", "b", "c"); 
// myArray is now ["1", "2", "3", "a", "b", "c"]
join(deliminator = ',') joins all elements of an array into a string.
var myArray = new Array("Wind", "Rain", "Fire");
var list = myArray.join(" - "); // list is "Wind - Rain - Fire"
push() adds one or more elements to the end of an array and returns the resulting length of the array.
var myArray = new Array("1", "2");
myArray.push("3"); // myArray is now ["1", "2", "3"]
pop() removes the last element from an array and returns that element.
var myArray = new Array("1", "2", "3");
var last = myArray.pop(); 
// myArray is now ["1", "2"], last = "3"
shift() removes the first element from an array and returns that element.
var myArray = new Array ("1", "2", "3");
var first = myArray.shift(); 
// myArray is now ["2", "3"], first is "1"
unshift() adds one or more elements to the front of an array and returns the new length of the array.
var myArray = new Array ("1", "2", "3");
myArray.unshift("4", "5"); 
// myArray becomes ["4", "5", "1", "2", "3"]
slice(start_index, upto_index) extracts a section of an array and returns a new array.
var myArray = new Array ("a", "b", "c", "d", "e");
myArray = myArray.slice(1, 4); // starts at index 1 and extracts all elements
                               // until index 3, returning [ "b", "c", "d"]
splice(index, count_to_remove, addElement1, addElement2, ...) removes elements from an array and (optionally) replaces them.
var myArray = new Array ("1", "2", "3", "4", "5");
myArray.splice(1, 3, "a", "b", "c", "d"); 
// myArray is now ["1", "a", "b", "c", "d", "5"]
// This code started at index one (or where the "2" was), 
// removed 3 elements there, and then inserted all consecutive
// elements in its place.
reverse() transposes the elements of an array: the first array element becomes the last and the last becomes the first.
var myArray = new Array ("1", "2", "3");
myArray.reverse(); 
// transposes the array so that myArray = [ "3", "2", "1" ]
sort() sorts the elements of an array.
var myArray = new Array("Wind", "Rain", "Fire");
myArray.sort(); 
// sorts the array so that myArray = [ "Fire", "Rain", "Wind" ]
sort() can also take a callback function to determine how array elements are compared. The function compares two values and returns one of three values:
For instance, the following will sort by the last letter of a string:
var sortFn = function(a, b){
  if (a[a.length - 1] < b[b.length - 1]) return -1;
  if (a[a.length - 1] > b[b.length - 1]) return 1;
  if (a[a.length - 1] == b[b.length - 1]) return 0;
}
myArray.sort(sortFn); 
// sorts the array so that myArray = ["Wind","Fire","Rain"]
  • if a is less than b by the sorting system, return -1 (or any negative number)
  • if a is greater than b by the sorting system, return 1 (or any positive number)
  • if a and b are considered equivalent, return 0.
indexOf(searchElement[, fromIndex]) searches the array for searchElement and returns the index of the first match.
var a = ['a', 'b', 'a', 'b', 'a'];
console.log(a.indexOf('b')); // logs 1
// Now try again, starting from after the last match
console.log(a.indexOf('b', 2)); // logs 3
console.log(a.indexOf('z')); // logs -1, because 'z' was not found
lastIndexOf(searchElement[, fromIndex]) works like indexOf, but starts at the end and searches backwards.
var a = ['a', 'b', 'c', 'd', 'a', 'b'];
console.log(a.lastIndexOf('b')); // logs 5
// Now try again, starting from before the last match
console.log(a.lastIndexOf('b', 4)); // logs 1
console.log(a.lastIndexOf('z')); // logs -1
forEach(callback[, thisObject]) executes callback on every array item.
var a = ['a', 'b', 'c'];
a.forEach(function(element) { console.log(element);} ); 
// logs each item in turn
map(callback[, thisObject]) returns a new array of the return value from executing callback on every array item.
var a1 = ['a', 'b', 'c'];
var a2 = a1.map(function(item) { return item.toUpperCase(); });
console.log(a2); // logs A,B,C
filter(callback[, thisObject]) returns a new array containing the items for which callback returned true.
var a1 = ['a', 10, 'b', 20, 'c', 30];
var a2 = a1.filter(function(item) { return typeof item == 'number'; });
console.log(a2); // logs 10,20,30
every(callback[, thisObject]) returns true if callback returns true for every item in the array.
function isNumber(value){
  return typeof value == 'number';
}
var a1 = [1, 2, 3];
console.log(a1.every(isNumber)); // logs true
var a2 = [1, '2', 3];
console.log(a2.every(isNumber)); // logs false
some(callback[, thisObject]) returns true if callback returns true for at least one item in the array.
function isNumber(value){
  return typeof value == 'number';
}
var a1 = [1, 2, 3];
console.log(a1.some(isNumber)); // logs true
var a2 = [1, '2', 3];
console.log(a2.some(isNumber)); // logs true
var a3 = ['1', '2', '3'];
console.log(a3.some(isNumber)); // logs false
The methods above that take a callback are known as iterative methods, because they iterate over the entire array in some fashion. Each one takes an optional second argument called thisObject. If provided, thisObject becomes the value of the this keyword inside the body of the callback function. If not provided, as with other cases where a function is invoked outside of an explicit object context, this will refer to the global object (window).
The callback function is actually called with three arguments. The first is the value of the current item, the second is its array index, and the third is a reference to the array itself. JavaScript functions ignore any arguments that are not named in the parameter list so it is safe to provide a callback function that only takes a single argument, such as alert.
reduce(callback[, initialValue]) applies callback(firstValue, secondValue) to reduce the list of items down to a single value.
var a = [10, 20, 30];
var total = a.reduce(function(first, second) { return first + second; }, 0);
console.log(total) // Prints 60
reduceRight(callback[, initalvalue]) works like reduce(), but starts with the last element.
reduce and reduceRight are the least obvious of the iterative array methods. They should be used for algorithms that combine two values recursively in order to reduce a sequence down to a single value.

Multi-dimensional arraysSección

Arrays can be nested, meaning that an array can contain another array as an element. Using this characteristic of JavaScript arrays, multi-dimensional arrays can be created.
The following code creates a two-dimensional array.
var a = new Array(4);
for (i = 0; i < 4; i++) {
  a[i] = new Array(4);
  for (j = 0; j < 4; j++) {
    a[i][j] = "[" + i + "," + j + "]";
  }
}
This example creates an array with the following rows:
Row 0: [0,0] [0,1] [0,2] [0,3]
Row 1: [1,0] [1,1] [1,2] [1,3]
Row 2: [2,0] [2,1] [2,2] [2,3]
Row 3: [3,0] [3,1] [3,2] [3,3]

Arrays and regular expressionsSección

When an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of RegExp.exec()String.match(), and String.split(). For information on using arrays with regular expressions, see Regular Expressions.

Working with array-like objectsSección

Some JavaScript objects, such as the NodeList returned by document.getElementsByTagName() or the arguments object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods. The arguments object provides a length attribute but does not implement the forEach() method, for example.
Array generics, provide a way of running Array methods against other array-like objects. Each standard array method has a corresponding method on the Array object itself; for example:
function printArguments() {
  Array.forEach(arguments, function(item) {
    console.log(item);
  });
}
These generic methods can be emulated more verbosely in older versions of JavaScript using the call method provided by JavaScript function objects:
Array.prototype.forEach.call(arguments, function(item) {
  console.log(item);
});
Array generic methods can be used on strings as well, since they provide sequential access to their characters in a similar way to arrays:
Array.forEach("a string", function(chr) {
  console.log(chr);
});

Array comprehensionsSección

Introduced in JavaScript 1.7 and proposed to be standardized in ECMAScript 7array comprehensions provide a useful shortcut for constructing a new array based on the contents of another. Comprehensions can often be used in place of calls to map() and filter(), or as a way of combining the two.
The following comprehension takes an array of numbers and creates a new array of the double of each of those numbers.
var numbers = [1, 2, 3, 4];
var doubled = [i * 2 for (i of numbers)];
console.log(doubled); // logs 2,4,6,8
This is equivalent to the following map() operation:
var doubled = numbers.map(function(i){return i * 2;});
Comprehensions can also be used to select items that match a particular expression. Here is a comprehension which selects only even numbers:
var numbers = [1, 2, 3, 21, 22, 30];
var evens = [i for (i of numbers) if (i % 2 === 0)];
console.log(evens); // logs 2,22,30
filter() can be used for the same purpose:
var evens = numbers.filter(function(i){return i % 2 === 0;});
map() and filter() style operations can be combined into a single array comprehension. Here is one that filters just the even numbers, then creates an array containing their doubles:
var numbers = [1, 2, 3, 21, 22, 30];
var doubledEvens = [i * 2 for (i of numbers) if (i % 2 === 0)];
console.log(doubledEvens); // logs 4,44,60
The square brackets of an array comprehension introduce an implicit block for scoping purposes. New variables (such as i in the example) are treated as if they had been declared using let. This means that they will not be available outside of the comprehension.
The input to an array comprehension does not itself need to be an array; iterators and generators can also be used.
Even strings may be used as input; to achieve the filter and map actions (under Array-like objects) above:
var str = 'abcdef';
var consonantsOnlyStr = [c for (c of str) if (!(/[aeiouAEIOU]/).test(c))  ].join(''); // 'bcdf'
var interpolatedZeros = [c+'0' for (c of str) ].join(''); // 'a0b0c0d0e0f0'
Again, the input form is not preserved, so we have to use join() to revert back to a string.

Typed ArraysSección

JavaScript typed arrays are array-like objects and provide a mechanism for accessing raw binary data. As you already know, Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast. However, as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using WebSockets, and so forth, it has become clear that there are times when it would be helpful for JavaScript code to be able to quickly and easily manipulate raw binary data in typed arrays.

Buffers and views: typed array architectureSección

To achieve maximum flexibility and efficiency, JavaScript typed arrays split the implementation into buffers and views. A buffer (implemented by the ArrayBuffer object) is an object representing a chunk of data; it has no format to speak of, and offers no mechanism for accessing its contents. In order to access the memory contained in a buffer, you need to use a view. A view provides a context — that is, a data type, starting offset, and number of elements — that turns the data into an actual typed array.
Typed arrays in an ArrayBuffer

ArrayBufferSección

The ArrayBuffer is a data type that is used to represent a generic, fixed-length binary data buffer. You can't directly manipulate the contents of an ArrayBuffer; instead, you create a typed array view or a DataView which represents the buffer in a specific format, and use that to read and write the contents of the buffer.

Typed array viewsSección

Typed array views have self descriptive names and provide views for all the usual numeric types like Int8Uint32Float64 and so forth. There is one special typed array view, the Uint8ClampedArray. It clamps the values between 0 and 255. This is useful for Canvas data processing, for example.
TypeValue RangeSize in bytesDescriptionWeb IDL typeEquivalent C type
Int8Array-128 to 12718-bit two's complement signed integerbyteint8_t
Uint8Array0 to 25518-bit unsigned integeroctetuint8_t
Uint8ClampedArray0 to 25518-bit unsigned integer (clamped)octetuint8_t
Int16Array-32768 to 32767216-bit two's complement signed integershortint16_t
Uint16Array0 to 65535216-bit unsigned integerunsigned shortuint16_t
Int32Array-2147483648 to 2147483647432-bit two's complement signed integerlongint32_t
Uint32Array0 to 4294967295432-bit unsigned integerunsigned longuint32_t
Float32Array1.2x10-38 to 3.4x1038432-bit IEEE floating point number ( 7 significant digits e.g. 1.1234567)unrestricted floatfloat
Float64Array5.0x10-324 to 1.8x10308864-bit IEEE floating point number (16 significant digits e.g. 1.123...15)unrestricted doubledouble
BigInt64Array-263 to 263-1864-bit two's complement signed integerbigintint64_t (signed long long)
BigUint64Array0 to 264-1864-bit unsigned integerbigintuint64_t (unsigned long long)
Fore more information, see JavaScript typed arrays and the reference documentation for the different TypedArray objects.
SHARE

Oscar perez

Arquitecto especialista en gestion de proyectos si necesitas desarrollar algun proyecto en Bogota contactame en el 3006825874 o visita mi pagina en www.arquitectobogota.tk

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comentarios:

Publicar un comentario