some() filter() forEach() map() reduce()

83 阅读1分钟

some()

some() 方法用于检测数组中的元素是否满足指定条件(函数提供)。 some() 方法会依次执行数组的每个元素:

  • 如果有一个元素满足条件,则表达式返回true ,* 剩余的元素不会再执行检测***。
  • 如果没有满足条件的元素,则返回false。
  • 返回值是true/false

例子:

item = [
{
    type: 'input'
    name: 'aaa'
},
{
    type: 'input'
    name: 'bbb'
},
{
    type: 'output'
    name: 'ccc'
}];
let index=-1;
items.some(item =>{ 
            if(option.type === 'input') index++;
            return item.name === 'bbb';
 })
 console.log(index);
 // 输出:1   
 // 剩余的元素不会再执行检测

forEach: 写了返回值也不会返回

const array1 = ['a', 'b', 'c'];

const a=array1.forEach(element => {
    return element
});
console.log(a);
> undefined

map

  • 写了return, 返回 值
  • 不写return, 返回[undefined,undefined,undefined]
  • 返回的是个新数组,就算给原数组的值重新赋值,也不影响原数组的值
const array1 = ['a', 'b', 'c'];

const array2=array1.map(element => {
     element=2;
    return element
});
console.log(array1)
console.log(array2)
> "array1-----a,b,c" 
> "array2-----2,2,2"

  • 但是如果是个数组对象,改变对象的属性值, 原数组的属性值也会改变 注意对象的内存地址没被改变
const array1 = [{name:'a',type:'go'}, {name:'b',type:'go'}];

const array2=array1.map(element => {
     element.name='c';
    return element
});
console.log(array1);
console.log(array2);
> Array [Object { name: "c", type: "go" }, Object { name: "c", type: "go" }]
> Array [Object { name: "c", type: "go" }, Object { name: "c", type: "go" }]