강의

멘토링

커뮤니티

Cộng đồng Hỏi & Đáp của Inflearn

Hình ảnh hồ sơ của mky980027
mky980027

câu hỏi đã được viết

Khóa học ES6 để phát triển JavaScript hiện đại

Được gắn thẻ Chữ mẫu

fn함수 리턴 값 순서에 관한 질문 입니다.

Viết

·

185

1

fn함수 리턴값으로 tags[0] + name + tags[1] + items + tags[2]; 이렇게 리턴 하셨는데

다음과 같이 리턴값을 매치 시키니깐 items + tags[2]가 왜 tags[2] + items 이렇게 되면 안되는지를 잘 모르겠습니다.

tags[0] + name => Welcome ${data[1].name}!!

tags[1] =>

주문가능항목

items + tags[2] => ${data[1].items} ??? <-- 이부분 tags[2] + items 되면 안되더라구요... 왜 그럴까요?

javascriptes6

Câu trả lời 1

0

함수로 전달되는 tags 매개변수는 "${v.name}", "${v.items}" 같이 "${ }" 부분을 기준으로 나뉘어진 배열로 전달됩니다.

따라서, fn`<h2>welcome ${v.name} !!</h2><h4>주문가능항목</h4><div>${v.items}</div>`

['<h2>welcome ' , ' !!</h2><h4>주문가능항목</h4><div>', '</div>'] 같은 tags 배열이 전달됩니다.

순차적으로 각각 tags[0], tags[1], tags[2] 되는 것이구요.

"tags[0] + name + tags[1] + items + tags[2]"

'<h2>welcome ' + name + ' !!</h2><h4>주문가능항목</h4><div>' + items + '</div>' 처럼 조립이 되어

원하는 HTML 구조를 형성할 있습니다.

<h2>welcome ${v.name} !!</h2>
<h4>주문가능항목</h4>
<div>${v.items}</div>

같이 말이죠.

하지만, items tags[2] 순서를 바꾸어 tags[2] + items 반환하면,

겉으로는 정상적으로 보이지만, 실제로 형성된 HTML 구조는 의도와는 다름을 있습니다.

<h2>welcome ${v.name} !!</h2>
<h4>주문가능항목</h4>
<div></div>${v.items}

마지막 줄이 바뀌었음을 있습니다.

다음과 같이 console.log() 함수를 통해 변수를 확인해보면 자세히 있습니다.

const data = [
  {
    name: "coffee-bean",
    order: true,
    items: ['americano', 'milk', 'green-tea']
  },
  {
    name: 'starbucks',
    order: false
  },
  {
    name: 'coffee-king',
    order: true,
    items: ['americano', 'latte']
  }
]

function fn(tags, name, items) {
  if(typeof items === "undefined") {
    items = "<span style='color:red'>주문가능한 상품이 없습니다</span>";
  }
  console.log(tags);
  return tags[0] + name + tags[1] + items + tags[2];
}

data.forEach((v) => {
  let template = fn`<h2>welcome ${v.name} !!</h2>
    <h4>주문가능항목</h4><div>${v.items}</div>`;
  
  console.log(template);
  document.querySelector("#message").innerHTML += template;
});
Hình ảnh hồ sơ của mky980027
mky980027

câu hỏi đã được viết

Đặt câu hỏi