Array


Javascript ES6,ES7,ES8

Array

Array.of

const friends = ["Euido", "Josh", "Paul", "Tidermann"];

const friends = Array.of("Euido", "Josh", "Paul", "Tidermann");

// two codes are same. 

Array.from
Let’s attach Event listner to each button
Example 1)

<body>
  <button>1</button>
  <button>2</button>  
  <button>3</button>
  <button>4</button>  
  <button>5</button>
  <button>6</button>  
  <button>7</button>
  <button>8</button>  
  <button>9</button>
  <button>10</button>   
</body>
const buttons = document.querySelectorAll("button");

console.log(buttons);
// result : we can get NodeList. Not array.

Example 2)

<body>
  <button class="btn">1</button>
  <button class="btn">2</button>  
  <button class="btn">3</button>
  <button class="btn">4</button>  
  <button class="btn">5</button>
  <button class="btn">6</button>  
  <button class="btn">7</button>
  <button class="btn">8</button>  
  <button class="btn">9</button>
  <button class="btn">10</button>  
</body>
const buttons = document.getElementByClassName("btn");

console.log(buttons);
// result : we can get HTMLCollection. Not array.

these are called “array-like object” not “array”
and “array-like object” has not forEach function not like “array”
so…. we should change the type as below.

Array.from(buttons).forEach(button => {
  button.addEventListener("click",() => console.log("I ve been clicked"));
})

Various Array functions
1.find

const friends = [
  "leeeuido@gmail.com"
  "leeeuido@naver.com"
  "leeeuido@daum.net"
  "mark@hanmail.com"
  "paul@lycos.com"
];

const target = friends.find(friend => friend.include("@gmail.com"));
// find try to execute friend.include("gmail.com") for each element of array.
// if they return first element which match with the condition.

console.log(target);
//result : leeeuido@gmail.com

2.index

const friends = [
  "leeeuido@gmail.com"
  "leeeuido@naver.com"
  "leeeuido@daum.net"
  "mark@hanmail.com"
  "paul@lycos.com"
];

const target = friends.findIndex(friend => friend.include("@gmail.com"));
// find try to execute friend.include("gmail.com") for each element of array.
// if they return index of the first element which match with the condition.

console.log(target);
//result : 0

3.fill

const friends = [
  "leeeuido@gmail.com"
  "leeeuido@naver.com"
  "leeeuido@daum.net"
  "mark@hanmail.com"
  "paul@lycos.com"
];

friends.fill("*".repeat("5"),1,2);
//fill(value:string, start?:number, end?:number)
console.log(friends);
//result : ["leeeuido@gmail.com", "*****", "*****", "mark@hanmail.com", "paul@lycos.com"]

4.include

const friends = [
  "leeeuido@gmail.com"
  "leeeuido@naver.com"
  "leeeuido@daum.net"
  "mark@hanmail.com"
  "paul@lycos.com"
];

console.log(friends.include("leeeuido@daum.net"));
include return true or false





© 2017. by isme2n

Powered by aiden