IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Javascript Array

    bear发表于 2024-01-11 16:24:39
    love 0

    Handle element in an Array

    const hobbies = ["sports", "cooking", "reading"];
    
    console.log(hobbies[0]);       # Get single element
    
    hobbies.push("surfing");       # Add new element to the end
    hobbies.unshift("movies");     # Add new element to th start
    
    hobbies.pop();                 # remove the last element
    hobbies.shift();               # remove the first element
    

    Find element

    const index = hobbies.findIndex((item) => {
        return item === "reading"
    });
    console.log(index);

    A shorter code:

    const index = hobbies.findIndex((item) => item === "reading");
    console.log(index);
    
    // Result
    2

    Filter & Find

    const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
    const result = words.filter((word) => word.length > 6);
    
    // Result:
    ["exuberant", "destruction", "present"]
    const inventory = [
      { name: "apples", quantity: 2 },
      { name: "bananas", quantity: 0 },
      { name: "cherries", quantity: 5 },
    ];
    
    const result = inventory.find(({ name,quantity }) => name === "cherries");
    
    console.log(result); 
    
    // Result:
     { name: 'cherries', quantity: 5 }

    find() method ONLY returns the first element in the provided array that satisfies the provided testing function

    Iterate Array

    const newHobbies = hobbies.map((item) => item + "!");
    consoloe.log(newHobbies);
    
    // Result
    (3) ["sports!", "cooking!", "reading!"]

    Combine Array

    const numbers = [1,2,4,5];
    const all = [...hobbies, ...numbers];
    console.log(all);
    
    // Result
    (7) ["sports", "cooking", "reading", 1, 2, 4, 5]

    Destruct an Array

    const userName = ["John", "Ted"];
    
    // Old School Way
    // const firstName = userName[0];
    // const lastName = userName[1];
    
    // New Way
    const [firstName, lastName] = ["John", "Ted"];
    console.log(firstName);
    console.log(lastName);
    
    // Result:
    John
    Ted

    We can also destruct an Object like this:

    const {name,quantity} = { name: "apples", quantity: 2 };
    console.log(name);
    console.log(quantity);
    
    // Result:
    apples
    2


沪ICP备19023445号-2号
友情链接