序言:好久没敲代码了,对于数组的操作的几个常用方法都有点遗忘了;这里复习一下;知识点都在下面代码的实例中;
const arr = [1, 2, 3, 5, 8, 4, 1]
//利用map进行求和计算
let sum = 0;
arr.map((item) => {
sum = item + sum
})
console.log(sum)//24
//对满足条件的元素进行操作
let temp = arr.map((item) => {
if (item == 1) {
item = item + 100;
}
return item;
})
console.log(temp)//[101,2,3,5,8,4,101]
//对所有元素进行操作
temp = arr.map((item) => {
item = item + 100;
return item;
})
console.log(temp)// [101,102,103,105,108,104,101]
//使用ruduce进行求和 注意参数有两个
let x = arr.reduce((acc, curr) => {
return acc + curr;
})
console.log(x)//24
//filter对数组元素进行筛选
let A = [-1,-2,-3,0,1,2,3]
let B = A.filter((item)=>{
return item>0;//返回大于0的元素
})
console.log(B)// [1,2,3]
//此外,map filter reduce都不会改变原数组的值;
console.log(A) // [-1,-2,-3,0,1,2,3]
console.log(arr) //[1,2,3,5,8,4,1]
//字符串加减法运算
const arr1 = ['-1', '+2', '-1']
let y = arr1.reduce((acc, curr) => {
//return parseInt(acc)+parseInt(curr);
return Number(acc) + Number(curr);
})
console.log(y) //0
//Number可以将空字符串转化为0
console.log(parseInt(''))
console.log(parseInt('')+parseInt(1))
console.log(Number(''))
console.log(Number('')+Number(1))
> NaN
> NaN
> 0
> 1
|