Array iteration : 8 methods in JS
阿新 • • 發佈:2019-01-02
//forEach()
//it's pretty straightforward, it just does something for each item in the array
[1,2,3].forEach(function(item,index){
console.log(item, index); // 1,0---2,1---3,2
});
//map()
//it takes the item that's from the array,
//it does something to it and then puts a new thing back in that same place in the array
const numbers = [1,2,3];
const doubled = numbers.map(function(item,index){
return item*2;
});
console.log(doubled); // [2,4,6]
console.log(numbers); // [1,2,3];
//filter()
//it's gonna take an array and it's gonna check each item in the array
//it gets again some kind of condition to see it it's true or false
//if it's true, it's going to put the item back in the array
const ints = [1,2,3];
const evens = ints.filter(function(item){
return item%2 === 0;
});
console.log(evens); // [2]
console.log(ints); // [1,2,3]
//reduce
//we're going to do something and then pass the result to the next iteration along with the next item in the array
//the number at the end is what the initial result is going to be
//if you don't put a number at the end like that
//the initial result will be the first item in the array
const sum = [1,2,3].reduce(function(result,item){
return result+item;
},0);
console.log(sum); // 6
//some()
//just check if any item in the array
//does any item in the entire array meet this condition
//so if any item in the entire array meets the condition
//it will return true
const hasNegativeNumbers = [1,2,3,-4].some(function(item){
return item < 0;
});
console.log(hasNegativeNumbers); // true
//every()
//it's kind of similar to some()
//but now every number has to meet the condition
const hasPositiveNumbers = [1,2,3].every(function(item){
return item > 0
});
console.log(hasPositiveNumbers); // true
//find()
//it goes through every item in the array
//and check it against the condition, if that's true, it returns that item
const objects = [{id:'a'},{id:'b'},{id:'c'}];
const found = objects.find(function(item){
return item.id === 'b';
});
console.log(found); // {id:'b'}
//findIndex()
const objects2 = [{id:'a'},{id:'b'},{id:'c'}];
const foundIndex = objects.findIndex(function(item){
return item.id === 'b';
});
console.log(foundIndex); // 1