JS 20 ways to control Array

main.jpg
splice
array.splice(startIndex , deleteCount, [addItem1, addItem2,…])
deleteCount <= 0 : not delete
deleteCount > 0 || > arry.length  : delete all after startIndex
 
reduce
var numbers = [1,2,3,4,5];
var sum = numbers.reduce(function(prev, next){
    return prev + next;
})
> 15
 
reduceRight
var arry = [“A","B","C"];
arry.reduceRight(function(prev, next){
    return prev+next;
})
“CBA"
V.S.
arry.reduce(function(prev, next){
    return prev+next;
})
“ABC"
sort
sort by 根據字串的 Unicode 編碼位置(A to Z) , 強行轉成字串
var ary = [14,5,1,30,62]
ary.sort();
> [1, 14, 30, 5, 62] //not sort by number
 
ary.sort(function(a,b){
    return a > b ? 1 : -1;
})
>  [1, 5, 14, 30, 62]
reverse
var ary = [14,5,1,30,62];
var arry = [“A","B","C", “D"];
ary.reverse()
> [62, 30, 14, 5, 1]
arry.reverse()
> [“D", “C", “B", “A"]
indexOf
-1 : not exist
>= 0 : index
repeat value : only show first mapping index
lastIndexOf : only show last mapping index
var ary = [14,5,1,30,62];
var arry = [“A","B","C", “D"];
ary.indexOf(“C")
-1
arry.indexOf(“C")
1
arry.indexOf(“A")
3
arry.push(“A")
5
arry
(5) [“D", “C", “B", “A", “A"]
arry.lastIndexOf(“A")
4
arry.indexOf(“A")
3
some V.S. every
some : fn will return true when one of elements is mapping
every :  fn will return true when all of elements are mapping
arry.some(function(val){
return val=="C";
})
true
arry.some(function(val){
return val=="AA";
})
false
arry.every(function(val){
return val=="C";
})
false
forEach
arr.forEach(function callback(currentValue[, index[, array]]) {
//your iterator
}[, thisArg]);
arry.forEach(function(val,index){
    console.log(index, val);
})
0 “D"
1 “C"
2 “B"
3 “A"
4 “A"
Pure function: 不影響原始Array元素的操作
map
arry.map(function(val, i){
    return val + val;
})
(5) [“DD", “CC", “BB", “AA", “AA"] //return new array
arry
(5) [“D", “C", “B", “A", “A"] //raw array not affected
filter
var n = [1,2,3,4,5,6,7,8,9,10];
n.filter(function(val){
    return val%2 === 0;
})
(5) [2, 4, 6, 8, 10]
var n = [1,2,3,4,5,6,7,8,9,10];
n.filter(function(val){
    return val%2 !== 0;
})
(5) [1, 3, 5, 7, 9]
slice
arr.slice([begin[, end]])
begin : >= index
end : < end
n.slice(2,8) // index: 2-7
(6) [3, 4, 5, 6, 7, 8]
concat
n.concat([11,12,13,14,15])
(15) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

1 thoughts on “JS 20 ways to control Array

發表留言