Object.entries(JSON_obj)
Object.is(obj1, obj2)
- 뭐가 다른기만 딱 뽑아주는 기능이 있다면 좋을텐데 인덱스 숫자로 데이터 접근하는건 가독성이 떨어짐
arr = [];
obj = {};
꼭 초기화 해야 (다른 원시 타입 변수와는 다름!) Range.range(0,100,2);
dynamic lookup
has its costs in efficiency. using hidden class
(v8 engine) guarantees efficiency, since it behaves similarly to fixed object layouts (class) undefined
as opposed to throwing a reference error let user = {
firstName: "Benjamin"
lastName: "L'Anusse"
email: 'blanusse@gmail.com'
city: 'Seoul'
}
let firstName = "Benjamin", lastName = "L'Annusse";
const obj = {firstName, lastName};
console.log(obj);
var prefix = 'prop';
var i = 0;
var obj = {};
obj[prefix + '-' + ++i] = i;
obj[prefix + '-' + ++i] = i;
obj[prefix + '-' + ++i] = i;
console.log(obj); // {prop-1: 1, prop-2: 2, prop-3: 3}
//ES6
const prefix = 'prop';
let i = 0;
const obj {
[`${prefix}-${++i}`]: i,
[`${prefix}-${++i}`]: i,
[`${prefix}-${++i}`]: i
};
console.log(obj) //{prop-1: 1, prop-2: 2, prop-3: 3}
const items = ["A", "B", "C"];
const obj = {
[items]: "Hello",
};
console.log(obj); // A,B,C: "Hello"
console.log(obj["A,B,C"]); // "Hello"
const param = 'size';
const config = {
[param]: 12,
[`mobile${param.charAt(0).toUpperCase()}${param.slice(1)}`]: 4,
};
console.log(config); // {size: 12, mobileSize: 4}
let objProperties = [];
let obj = {};
function createProperties(prefix, num, arr) {
for (let i = 0; i < num; i++) {
arr[i] = `${prefix}-${i + 1}`;
}
}
function createObjectWithPropertyArray(obj, propArray) {
for (let i = 0; i < propArray.length; i++) {
obj[propArray[i]] = i + 1;
}
}
createProperties('prop', 50, objProperties);
createObjectWithPropertyArray(obj, objProperties);
console.log(obj);
user.firstName
: dot notation - accessing properties (속성) user['firstName']
: bracket notation - 문자열로 key를 써야 함 user[firstName]
: firstName이란 변수를 넣어줌ReferenceError: name is not defined
user['category'] = missing
--- 추가 가능 (동적 생성) delete user.category
--- 삭제 가능 'email' in user
//true 'secondCity' in user
//false//ES5
var obj = {
name: 'Lee',
sayHi: function(){
console.log('Hi! ' + this.name);
}
}
obj.sayHi(); //Hi! Lee
//ES6
var obj = {
name = 'Lee',
sayHi(){
console.log('Hi! ' + this.name);
}
}
obj.sayHi();
Object.keys()
- spits out keys in an arrayObject.keys(obj).length
- length of keys Object.values()
Object.assign(obj1, obj2)
- 합치는 것. 똑같은 속성은 obj2로 덮어쓰게 됨 arr.slice()
처럼 사용 가능 - let obj1 = Object.assign({}, obj2)
Object.is(obj1, obj2)
두개의 객체 비교 // true if equivalent, false otherwise for..in
loopfor (let key in obj) {}
: iterates key after key in object
let mobile = {
brand: 'Samsung',
model: 'Galaxy Note 9'
};
for (let key in mobile) {
console.log(`${key}: ${mobile[key]}`);
}
allows object properties to be extracted into specific variable values
uses a pair of curly braces ({}) with property names on the left-hand side of an assignment to extract values from objects. The number of variables can be less than the total properties of an object
const rubiksCubeFacts = {
possiblePermutations: '43,252,003,274,489,856,000',
invented: '1974',
largestCube: '17x17x17'
};
const {possiblePermutations, invented, largestCube} = rubiksCubeFacts;
console.log(possiblePermutations); // '43,252,003,274,489,856,000'
console.log(invented); // '1974'
console.log(largestCube); // '17x17x17'
When JavaScript objects are passed as arguments to functions or methods, they are passed by reference, not by value. This means that the object itself (not a copy) is accessible and mutable (can be changed) inside that function. (reference)
const origNum = 8;
const origObj = {color: 'blue'};
const changeItUp = (num, obj) => { num = 7, obj.color = 'red';};
changeItUp(origNum, origObj); ;
// Will output 8 since integers are passed by value.
console.log(origNum);
// Will output 'red' since objects are passed
// by reference and are therefore mutable.
console.log(origObj.color);
this
keywordthis
context str.trim().length
: 공백을 제외한 길이! g : 모든 패턴 체크(global)
i : 대소문자를 구별없이 체크
m : 여러줄 체크
^ : 처음 | $ : 끝 | . : 한문자
.replace(' ','')
: 첫번째 공백 제거
.replace(/\-/g,'')
: - 제거
.replace(/[-]/g,'')
.replace(/,/g,'')
: , 제거
.replace(/^\s+/,'')
: 앞의 공백 제거
.replace(/\s+$/,'')
: 뒤의 공백 제거
.replace(/^\s+|\s+$/g,'')
: 앞뒤 공백 제거
.replace(/\s/g,'')
: 문자열 내의 모든 공백 제거
- str = str.replace(/\s/g, '');
- 문자 내의 모든 공백 제거
<문제 풀이>
//문자열을 입력받아 가장 많이 반복되는 문자(letter)를 리턴해야 합니다
// - 띄어쓰기는 제외합니다.
// - 가장 많이 반복되는 문자가 다수일 경우, 가장 먼저 해당 횟수에 도달한 문자를 리턴해야 합니다.
// - 빈 문자열을 입력받은 경우, 빈 문자열을 리턴해야 합니다.
function mostFrequentCharacter(str) {
if (str.trim().length === 0) return ''; //gets rid of spaces
str = str.replace(/\s+/g, ''); //replaces spaces with ''
let obj = {};
let freqCh = str[0];
for (i = 0; i < str.length; i++) {
if (obj[str[i]] === undefined) obj[str[i]] = 0;
obj[str[i]]++;
for (let key in obj) {
if (obj[key] > obj[freqCh]) freqCh = key; //비교구문
}
}
// for(let key in obj){
// if (obj[key] > obj[freqCh]) freqCh = key;
// }
return freqCh;
}
//참조 - 객체에 변수 모음을 집어넣음!
function mostFrequentCharacter(str) {
let obj = { mostCount: 0, mostFrequent: '' };
for (let i = 0; i < str.length; i++) {
if (str[i] === ' ') continue;
if (obj[str[i]] === undefined) obj[str[i]] = 0;
obj[str[i]] += 1;
if (obj[str[i]] > obj['mostCount']) {
obj['mostCount'] = obj[str[i]];
obj['mostFrequent'] = str[i];
}
}
return obj['mostFrequent'];
}
체크: