01. 객체의 기본
- 요소란 배열 내부에 있는 값을 말합니다.
- 속성은 객체 내부에 있는 값을 의미합니다.
- 메소드는 속성 중에 함수 자료형인 것을 의미합니다.
- this 키워드는 객체 내부의 메소드에서 객체 자신을 나타내는 키워드입니다.
- 객체 생성 이후에 속성을 추가하거나 제거하는 것을 동적 속성 추가, 동적 속성 제거라고 합니다.
확인 문제
01. 다음과 같은 대상을 자바스크립트 객체로 선언해주세요. 자료형은 알맞다고 생각하는 것(문자열, 숫자, 불 등)으로 지정해 주세요.
속성 이름 |
속성 값 |
name |
혼자 공부하는 파이썬 |
price |
18000 |
publisher |
한빛미디어 |
02. 다음 중 객체에 동적으로 속성을 추가하는 문법을 고르세요.
add 객체[속성] = 값
객체.add('속성', 값)
객체[속성] = 값
객체[속성] add 값
03. 다음 중 객체에 동적으로 속성을 제거하는 문법을 고르세요.
delete 객체[속성]
객체.delete(‘속성’)
delete 객체 from 속성
delete 속성 from 객체
04. 다음 코드에서 메소드라고 부를 수 있는 속성에 동그라미 표시하세요. 그리고 코드의 실행 결과를 예측해 보세요.
<script>
const object = {
ko: "빵",
en: "bread",
ja: "パン",
fr: "pain",
es: "pan",
lang: {
ko: "한국어",
en: "영어",
ja: "일본어",
fr: "프랑스어",
es: "스페인어",
},
print: function (lang) {
console.log(`${this.ko}는 ${this.lang[lang]}로 ${this[lang]}입니다.`);
},
};
object.print("es");
</script>
코멘트
01. 다음과 같은 대상을 자바스크립트 객체로 선언해주세요. 자료형은 알맞다고 생각하는 것(문자열, 숫자, 불 등)으로 지정해 주세요.
속성 이름 |
속성 값 |
name |
혼자 공부하는 파이썬 |
price |
18000 |
publisher |
한빛미디어 |
<script>
const object = {
name : '혼자 공부하는 파이썬',
price : 18000,
publisher : '한빛미디어'
}
</script>
02. 다음 중 객체에 동적으로 속성을 추가하는 문법을 고르세요.
객체[속성] = 값
03. 다음 중 객체에 동적으로 속성을 제거하는 문법을 고르세요.
delete 객체[속성]
04. 다음 코드에서 메소드라고 부를 수 있는 속성에 동그라미 표시하세요. 그리고 코드의 실행 결과를 예측해 보세요.
<script>
const object = {
ko: "빵",
en: "bread",
ja: "パン",
fr: "pain",
es: "pan",
lang: {
ko: "한국어",
en: "영어",
ja: "일본어",
fr: "프랑스어",
es: "스페인어",
},
// 여기부터 메소드입니다.
print: function (lang) {
console.log(`${this.ko}는 ${this.lang[lang]}로 ${this[lang]}입니다.`);
},
// 여기까지 메소드입니다.
};
object.print("es"); // 빵는 스페인어로 pan입니다.
</script>
02. 객체의 속성과 메소드 사용하기
- 실체가 있는 것 중에서 객체가 아닌 것을 기본 자료형이라고 하며, 숫자, 문자열, 불이 대표적인 예입니다.
- 객체를 기반으로하는 자료형을 객체 자료형이라고 하며,
new
키워드를 활용해서 생성합니다.
- 기본 자료형의 승급이란 기본 자료형이 일시적으로 객체 자료형으로 변화하는 것을 의미합니다.
- prototype 객체란 객체의 틀을 의미하며, 이곳에 속성과 메소드를 추가하면 해당 객체 전체에서 사용할 수 있습니다.
확인 문제
01. 다음 코드의 실행 결과를 예측해 보세요. 예측과 다른 결과가 나온다면 왜 그런지 생각해 보세요.
<script>
const num = 52000;
num.원 = function () {
return this.valueOf() + "원";
};
console.log(num.원());
</script>
02. 다음 코드의 실행 결과를 예측해 보세요.
<script>
function printLang(code) {
return printLang._lang[code];
}
printLang._lang = {
ko: "한국어",
en: "영어",
ja: "일본어",
fr: "프랑스어",
es: "스페인어",
};
console.log('printLang("ko"):', printLang('ko'))
console.log('printLang("en"):', printLang('en'))
</script>
03. 모질라 문서에서 Math 객체와 관련된 내용을 읽고 사인 90도의 값을 구해보세요. 참고로 사인 90도는 1입니다. 아주 단순하게 생각해서 구현하면 0.8939966636005579라는 결과가 나옵니다. 0.8939966636005579가 나왔다면 왜 그런지, 그리고 이를 어떻게 해야 제대로 사용할 수 있는지 구글 검색 등을 활용해서 알아보고 코드를 수정하세요.
<script>
// 변수를 선언합니다.
const degree = 90;
// 출력합니다.
</script>
04. 다음 중 어떤 종류의 객체들이 모두 공유하는 속성과 메소드를 추가할 때 사용하는 객체의 이름을 골라주세요.
- classProp
- prototype
- sample
- frame
05. 본문에서는 Lodash 라이브러리의 _sortBy()
메소드를 살펴보았습니다. _orderBy()
메소드도 한번 살펴보고 어떤 형태로 사용해야하는지 직접 예제를 작성해보세요. 그리고 다음과 같은 배열을 이름(name)으로 오름차순 정렬해 주세요.
<script>
const books = [{
name: '혼자 공부하는 파이썬',
price: 18000,
publisher: '한빛미디어'
}, {
name: 'HTML5 웹 프로그래밍 입문',
price: 26000,
publisher: '한빛아카데미'
}, {
name: '머신러닝 딥러닝 실전 개발 입문',
price: 30000,
publisher: '위키북스'
}, {
name: '딥러닝을 위한 수학',
price: 25000,
publisher: '위키북스'
}
]
</script>
코멘트
01. 다음 코드의 실행 결과를 예측해 보세요. 예측과 다른 결과가 나온다면 왜 그런지 생각해 보세요.
<script>
const num = 52000;
num.원 = function () {
return this.valueOf() + "원";
};
console.log(num.원());
</script>
// 실행되지 않습니다.
// num은 객체가 아닌 일반 자료형이므로 메소드를 가질 수 없습니다.
02. 다음 코드의 실행 결과를 예측해 보세요.
<script>
function printLang(code) {
return printLang._lang[code];
}
printLang._lang = {
ko: "한국어",
en: "영어",
ja: "일본어",
fr: "프랑스어",
es: "스페인어",
};
console.log('printLang("ko"):', printLang('ko'))
console.log('printLang("en"):', printLang('en'))
// printLang("ko"): 한국어
// printLang("en"): 영어
// printLang(code) 는 printLang._lang[code]를 반환하므로
// printLang('ko')는 한국어를 printLang('en')는 영어를 출력합니다.
</script>
03. 모질라 문서에서 Math 객체와 관련된 내용을 읽고 사인 90도의 값을 구해보세요. 참고로 사인 90도는 1입니다. 아주 단순하게 생각해서 구현하면 0.8939966636005579라는 결과가 나옵니다. 0.8939966636005579가 나왔다면 왜 그런지, 그리고 이를 어떻게 해야 제대로 사용할 수 있는지 구글 검색 등을 활용해서 알아보고 코드를 수정하세요.
<script>
// 변수를 선언합니다.
const degree = 90;
const rad = Math.PI / 180;
// 출력합니다.
console.log(Math.sin(degree * rad));
// Math.sin()은 우리가 사용하는 각도를 사용하는 것이 아닌 라디안 값을 사용합니다.
// 라디안 : 반지름과 호의 길이가 같을 때의 중심각의 크기 약 57.3도
// 부채꼴의 중심각과 호의 길이, 면적은 정비례한다는 성질을 이용하여 보대 간단하게 호의 길이, 면적을 구할 수 있기 때문입니다.
// 180도는 1pirad : 라디언 값 = 각도 * Math.PI / 180
</script>
04. 다음 중 어떤 종류의 객체들이 모두 공유하는 속성과 메소드를 추가할 때 사용하는 객체의 이름을 골라주세요.
- prototype
05. 본문에서는 Lodash 라이브러리의 _sortBy()
메소드를 살펴보았습니다. _orderBy()
메소드도 한번 살펴보고 어떤 형태로 사용해야하는지 직접 예제를 작성해보세요. 그리고 다음과 같은 배열을 이름(name)으로 오름차순 정렬해 주세요.
<script>
// _.orderBy(collection, [iteratees=[_.identity]], [orders])]
// # 인수
// collection (Array | Object) : 반복할 컬렉션
// [iteratees=[_.identity]] (Array[]|Function[]|Object[]|string[]) : 정렬할 반복 대상입니다.
// [orders] (string[]) : 의 정렬 순서입니다 iteratees.
// 기본 값 오름차순 -> 내림차순 "desc", 오름차순 정렬의 경우 "asc"
const books = [
{
name: "혼자 공부하는 파이썬",
price: 18000,
publisher: "한빛미디어",
},
{
name: "HTML5 웹 프로그래밍 입문",
price: 26000,
publisher: "한빛아카데미",
},
{
name: "머신러닝 딥러닝 실전 개발 입문",
price: 30000,
publisher: "위키북스",
},
{
name: "딥러닝을 위한 수학",
price: 25000,
publisher: "위키북스",
},
];
console.log(_.orderBy(books, ["name"], ["asc"]));
// books에서 "name"을 기준으로 오름차순("asc")으로 정렬
// 0: {name: 'HTML5 웹 프로그래밍 입문', price: 26000, publisher: '한빛아카데미'}
// 1: {name: '딥러닝을 위한 수학', price: 25000, publisher: '위키북스'}
// 2: {name: '머신러닝 딥러닝 실전 개발 입문', price: 30000, publisher: '위키북스'}
// 3: {name: '혼자 공부하는 파이썬', price: 18000, publisher: '한빛미디어'}
</script>
03. 객체와 배열 고급
- 속성 존재 여부 확인은 객체 내부에 어떤 속성이 있는지 확인하는 것을 의미합니다. 객체에 없는 속성은 접근하면 undefined가 나오는데, 이를 활용하면 됩니다.
- 다중 할당은 배열과 객체 하나로 여러 변수에 값을 할당하는 것을 의미합니다.
- 앏은 복사(참조 복사)는 복사하는 행위가 단순하게 다른 이름을 붙이는 형태로 동작하는 복사를 의미합니다.
- 깊은 복사는 복사 후 두 객체를 완전하게 독립적으로 사용할 수 있는 복사를 의미합니다.
확인 문제
01. 다음 중 전개 연산자의 형태로 올바른 것을 골라주세요.
~
...
@
spread
02. 구글에 “popular javascript libraries 2020” 등으로 검색해서 자바스크립트 라이브러리를 살펴본 후, 이름을 7개만 적어주세요.
코멘트
01. 다음 중 전개 연산자의 형태로 올바른 것을 골라주세요.
...
02. 구글에 “popular javascript libraries 2020” 등으로 검색해서 자바스크립트 라이브러리를 살펴본 후, 이름을 7개만 적어주세요.
- jQuery
더보기
jQuery is a classic JavaScript library that’s fast, light-weight, and feature-rich. It was built in 2006 by John Resig at BarCamp NYC. jQuery is free and open-source software with a license from MIT.
It makes things simpler for HTML document manipulation and traversal, animation, event handling, and Ajax.
According to W3Techs, 77.6% of all sites use jQuery (as of 23rd February 2021).
Features/Benefits:
It has an easy-to-use, minimalistic API.
It uses CSS3 selectors in manipulating style properties and finding elements.
jQuery is lightweight, taking just 30 kb to gzip and minify, and supports an AMD module.
As its syntax is quite similar to that of CSS, it is easy for beginners to learn.
Extendable with plugins.
Versatility with an API that supports multiple browsers, including Chrome and Firefox.
Use cases:
DOM manipulation with CSS selectors that use certain criteria to select a node in the DOM. These criteria include element names and their attributes (like class and id).
Element selection in DOM using Sizzle (an open-source, multi-browser selector engine).
Creating effects, events, and animations.
JSON parsing.
Ajax application development.
Feature detection.
Control of asynchronous processing with Promise and Deferred objects.
- React.js
더보기
React.js (also known as ReactJS or React) is an open-source, front-end JavaScript library. It was created in 2013 by Jordan Walke, who works at Facebook as a software engineer.
Now, it has the MIT license but was initially released under the Apache License 2.0. React was designed to make interactive UI creations painless.
Just design a simple view for individual states in your app. Next, it will render and update the right component efficiently upon data changes.
Features/Benefits:
The React code comprises components or entities that need rendering to a specific element in DOM with the help of a React DOM library.
It uses a virtual DOM by creating an in-memory cache in a data structure, computing the difference, and updating the display DOM in the browser efficiently.
Due to this selective rendering, the app performance boosts while saving the developers’ efforts in recalculating the page layout, CSS styles, and full-page rendering.
It uses lifecycle methods like render and componentDidMount to allow code execution at specific points during an entity’s lifetime.
It supports JavaScript XML (JSX) that combines both JS and HTML. It helps in component rendering with nested elements, attributes, JS expressions, and conditional statements.
Use cases:
Serving as the base while developing mobile or single-page applications.
Rendering a state to the DOM and manages it.
Building efficient user interfaces while developing web applications and interactive sites.
Debugging and testing more easily.
A bonus point: Facebook, Instagram, and Whatsapp all use React.
- D3.js
더보기
Data-Driven Documents (D3) or D3.js is another famous JS library that developers use to document manipulation based on data. It was released in 2011 under the BSD license.
Features/Benefits:
It emphasizes web standards and provides you with modern browser capabilities without being limited to a single framework.
D3.js enables powerful data visualizations.
It supports HTML, CSS, and SVG.
Takes a data-driven approach and applies it to manipulate the DOM.
D3.js is fast and supports a wide number of dynamic behavior and datasets for animations and interaction.
It reduces overhead, allowing wider graphical complexity within high frame-rates.
Use cases:
To produce interactive and dynamic data visualization.
To bind data to a DOM and perform a data-driven transformation on them. For example, you can generate HTML tables out of a numbers array and then create an SVG bar-chart or a 3D surface plot using D3.js.
Its functional code makes it reusable with a vast collection of modules.
D3 provides various modes to mutate nodes like changing styles or attributes by taking a declarative approach, adding, sorting, or removing nodes, changing text or HTML content, etc.
To create animated transitions, sequencing complex transitions through events, performing CSS3 transitions, etc.
- Underscore.js
더보기
Underscore is a JavaScript utility library that provides various functions for typical programming tasks. It was created in 2009 by Jeremy Askenas and release with an MIT license. Now, Lodash has overtaken it.
Features/Benefits:
Its features are similar to Prototype.js (another popular utility library), but Underscore has a functional programming design rather than object prototype extensions.
It has 100+ functions of 4 different types based on the datatypes they manipulate. These are functions to manipulate:
Objects
Arrays
Both objects and arrays
Other functions
Underscore is compatible with Chrome, Firefox, Edge, and more.
Use cases:
It supports functional helpers such as filters, maps, etc., along with specialized functions such as binding, quick indexing, JavaScript templating, quality testing, etc.
- Lodash
더보기
Lodash is also a JS utility library that makes it easier to work with numbers, arrays, strings, objects, etc. It was released in 2013 and also uses functional programming design like Underscore.js.
Features/Benefits:
It helps you write maintainable and concise JavaScript codes.
Simplifies common tasks such as math operations, binding, throttling, decorating, constraining, debouncing, etc.
String functions like trimming, camel case, and upper case are made simpler.
Creating, modifying, compressing, and sorting arrays.
Other operations on the collection, object, and sequence.
Use cases:
Its modular methods help you in:
Iterating arrays, strings, and objects.
Crafting composite functions.
Manipulating and testing values.
- Algolia Places
더보기
Algolia Places is a JavaScript library that provides an easy and distributed way of using address auto-completion on your site. It’s a blazingly fast and wonderfully accurate tool that can help increase your site user experience. Algolia Places leverages the impressive open-source database of OpenStreetMap to cover worldwide places.
For example, you can use it to boost your product page conversions.
Features/Benefits:
It simplifies checkouts by filling up multiple inputs simultaneously.
You can use the country or city selector effortlessly.
You can view results quickly by displaying link suggestions on a map in real-time.
Algolia Places can handle typing mistakes and displays results accordingly.
It delivers results within milliseconds by routing all queries automatically to their closest server.
Use cases:
Allows you to incorporate a map to display a specific location that is quite useful.
It enables you to use forms efficiently.
- Anime.js
더보기
If you want to add animations to your site or application, Anime.js is one of the best JavaScript libraries you can find. It was released in 2019 and is lightweight with a powerful yet simple API.
Features/Benefits:
Anime.js runs with DOM attributes, CSS properties, SVG, CSS transforms, and JS objects.
Works with a wide range of browsers such as Chrome, Safari, Firefox, Opera, etc.
Its source code is effortless to decipher and use.
Complex animation methods such as overlapping and staggering follow-through become easier.
Use cases:
You can use Anime.js’ staggering system on properties and timings.
Create layered CSS transformations with multiple timings simultaneously over one HTML element.
Play, pause, trigger, reverse, and control events in synchronizing manner using Anime.js call-backs and controls functions.