Вы находитесь на странице: 1из 3

Javascript ES6

Array Helpers
foreach()

Intro

var myArray = ['firstItem', 'secondItem', 'thirdItem'];


myArray.forEach(function(item) {
console.log(item);
});
/*
Output (in console):
firstItem
secondItem
thirdItem
*/

Example: sum of numbers

var numbers = [4, 5, 18, 3, 21, 25, 9];


var sum = 0;
numbers.forEach(function(number) {
sum += number;
});
console.log(sum);
/*
Output (in console):
85
*/

map()

Intro

var nums = [1, 2, 3, 4];


var doubledNums = nums.map(function(num) {
return num*2;
});
console.log(doubledNums);
/*

1/3
Output (in console):
[2, 4, 6, 8]
*/

Example: prices of cars

var cars = [
{model : 'Buick', price: '10k'},
{model : 'Camaro', price: '40k'}
];
var prices = cars.map(function(car) {
return car.price;
});
console.log(prices);
/*
Output (in console):
['10k', '40k']
*/

filter()

Intro (Example: grocer y shop products)

var products = [
{name: 'cucumber', type: 'vegetable'},
{name: 'celery', type: 'vegetable'},
{name: 'banana', type: 'fruit'},
{name: 'tomato', type: 'fruit'}
];
var fruits = products.filter(function(product) {
return product.type === 'fruit';
});
console.log(fruits);
/*
Output (in console):
[{"name":"banana","type":"fruit"},
{"name":"tomato","type":"fruit"}]
*/

Example: grocer y shop products (continued)

var products = [
{name: 'cucumber', type: 'vegetable', price: 1 },

2/3
{name: 'celery', type: 'vegetable', price: 3},
{name: 'banana', type: 'fruit', price: 2},
{name: 'tomato', type: 'fruit' price: 2}
];
var affordableVegs = products.filter(function(product) {
return product.type === 'vegetable' && product.price < 3;
});
console.log(affordableVegs);
/*
Output (in console):
[{"name":"banana","type":"fruit","price":1}]
*/

3/3

Вам также может понравиться