数组常用方法总结

  1.  判断数组中是否存在某个值

    var arrData = ['html', 'css', 'javascript'];
    var value = 'css';
    
    console.log(arrData.includes(value));
    console.log(arrData.some(item => item === value));
    console.log(arrData.indexOf(value) < 0 ? false : true);
    console.log(arrData.findIndex(item => item === value) < 0 ? false : true);
    console.log(arrData.find(item => item === value) !== undefined ? true : false );
    var arrData = [{ name: 'html' }, { name: 'css' }, { name: 'javascript' }];
    var value = 'css';
    
    console.log(arrData.some(item => item.name === value));
    console.log(arrData.filter(item=> item.name === value)[0] ? true : false);
    console.log(arrData.find(item => item.name === value) ? true : false);
  2.  数组去重

    var arrData = ['html', 'css', 'javascript', 'css'];
    
    console.log([...new Set(arrData)]);
    console.log(Array.from(new Set(arrData)));
    console.log(arrData.filter((item, index, slef) => slef.indexOf(item) === index));
    console.log(arrData.reduce((prev, cur) => prev.includes(cur) ? prev : [...prev, cur], []));

     

     

posted @ 2022-09-22 12:46  一丝心情  阅读(31)  评论(0编辑  收藏  举报