惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog
B
Blog RSS Feed
小众软件
小众软件
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 聂微东
WordPress大学
WordPress大学
月光博客
月光博客
S
SegmentFault 最新的问题
Engineering at Meta
Engineering at Meta
量子位
V
Visual Studio Blog
罗磊的独立博客
Last Week in AI
Last Week in AI
The Cloudflare Blog
H
Help Net Security
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Azure Blog
Microsoft Azure Blog
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队

月与灯依旧

回国见闻 – 月与灯依旧 Set up self-hosted runners for Github Actions – 月与灯依旧 Get Ubuntu release code name in Script – 月与灯依旧 大学回忆录之2023 – 月与灯依旧 found a tab character that violates indentation – 月与灯依旧 那些年,我所呆过的互联网公司 – 月与灯依旧 The easiest way to build a http/ftp server with Python – 月与灯依旧 pproxy简单介绍 – 月与灯依旧 How to add or remove a directory from media library on Windows – 月与灯依旧
Javascript Array – 月与灯依旧
by bear · 2024-01-12 · via 月与灯依旧

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

Find an element in Object

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

Filter

const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) => word.length > 6);

// Result:
["exuberant", "destruction", "present"]

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