Crear un Array en javascript:
isArray
indexOf / lastIndexOf
var myArray = ['1', '2', '3'];
push / pop
myArray.push('4'); // añade el numero 4 al final.
console.log(myArray); // Muestra por pantalla: '1', '2', '3', '4'
console.log(myArray.pop());
// Imprime por pantalla ('4) ya que el metodo pop elimina el último elemento del array.
console.log(myArray); // Imprime 1', '2', '3'
shift / unshift
myArray.unshift('0'); // Añade '0' at en la primera posición del Array
console.log(myArray); // Imprime '0','1', '2', '3'
console.log(myArray.shift()); // Imprime '0', pues el metodo shift elimina el primer elemento del array
console.log(myArray); // Imprime '1', '2', '3'
isArray
var myArray=['apple','samsung','blackberry'];
var myNoArray="I'm not an array";
//Array.IsArray(parameter) function returns true if the parameter passed is an array, false if not.
console.log(Array.isArray(myArray)); //Will render true
console.log(Array.isArray(myNoArray)); //Will render true
indexOf / lastIndexOf
var myArray=['car','apple','glass']; //creates an array with three items.
myArray.unshift('apple') //adds another "apple" element at the beginning of the array
//IndexOf function returns the lowest position of an element where the value is located (starting from 0), if no value returns -1
console.log(myArray.indexOf('apple')); // Will render 0.
//lastIndexOf function returns the greatest position of an element where the value is located (starting from 0), if no value returns -1
console.log(myArray.lastIndexOf('apple')); // Will render 2.
forEach
//creates an array with few elements
var myArray = ['apple', 'samsung', 'nokia', 'blackberry', 'lg', 'acer', 'huawei', 'xiaomi', 'miuzu', 'alcatel'];
/************ Array.forEach function **************/
console.log('/************ Array.forEach function ******************/');
myArray.forEach(function(value) {
console.log(value);
});
map
//creates an array with few elements
var myArray = [1, 2, 3, 4, 5];
/************ Array.map function ******************/
console.log('/************ Array.map function ******************/');
var TwoTimes = function(item) {
return item*2;
};
var TwoTimesArray=myArray.map(TwoTimes);
console.log(TwoTimesArray);
filter
//creates an array with few elements
var myArray = ['apple', 'samsung', 'nokia', 'blackberry', 'lg', 'acer', 'huawei', 'xiaomi', 'miuzu', 'alcatel'];
/*********** Array.filter function *****************/
console.log('/************ Array.filter function ******************/');
var myNewArray = myArray.filter(function(arrayItem) { //returns an array that contains all elements of an array for which the provided filter anonymous function returns true
if (arrayItem.indexOf('a') == 0) // item starts with 'a'
{
return true;
}
return false;
});
console.log(myNewArray); //render on console new array generated
No hay comentarios:
Publicar un comentario