ECMAScript 5(ES5)는 2009년에 표준화된 자바스크립트 버전으로, 오늘날 대부분의 브라우저와 환경에서 완벽히 지원됩니다.
ES5에서 새롭게 추가된 배열 메서드들과 기존 객체 메서드들은 실무에서 매우 자주 쓰이며, 이후 버전(ES6+)의 토대가 됩니다.
var arr = [1, 2, 3, 4];
console.log(arr.length); // 4
console.log(arr[0]); // 1arr.forEach(function(num, idx) {
console.log(idx, num);
});var squared = arr.map(function(x) {
return x * x;
});
// [1, 4, 9, 16]var even = arr.filter(function(x) {
return x % 2 === 0;
});
// [2, 4]truearr.some(function(x) {
return x > 3;
}); // truetruearr.every(function(x) {
return x > 0;
}); // true[1, 2, 3, 2].indexOf(2); // 1
[1, 2, 3, 2].lastIndexOf(2); // 3[1,2,3].join("-"); // "1-2-3"var sum = arr.reduce(function(acc, cur) {
return acc + cur;
}, 0);
// 10var str = ["a","b","c"].reduceRight(function(acc, cur) {
return acc + cur;
}, "");
// "cba"var a = [1,2,3];
a.push(4); // [1,2,3,4]
a.pop(); // [1,2,3]
a.shift(); // [2,3]
a.unshift(0); // [0,2,3]
a.slice(1,2); // [2]
a.splice(1,1,"X"); // [2] 반환, 원본: [0,"X",3]
a.concat([4,5]); // [0,"X",3,4,5]
a.reverse(); // ["X",0,3]
a.sort(); // 사전순 정렬var user = { name: "Alice", age: 25 };
console.log(user.name); // "Alice"
console.log(user["age"]); // 25Object.keys(user); // ["name", "age"]var proto = { greet: function() { return "hi"; } };
var obj = Object.create(proto);
obj.greet(); // "hi"var obj = {};
Object.defineProperty(obj, "x", {
value: 10,
writable: false,
enumerable: true
});
console.log(obj.x); // 10
obj.x = 20; // 무시됨var person = {};
Object.defineProperties(person, {
name: { value: "Bob", writable: true },
age: { value: 30, writable: false }
});Object.getOwnPropertyDescriptor(person, "age");
// { value:30, writable:false, enumerable:false, configurable:false }var obj2 = { a: 1 };
Object.freeze(obj2);
// obj2.a = 2; // 무시됨
var obj3 = { b: 2 };
Object.seal(obj3);
// obj3.c = 3; // 추가 불가
obj3.b = 5; // 수정 가능var users = [
{ name: "Kim", age: 20 },
{ name: "Lee", age: 30 }
];
var adults = users.filter(function(u) {
return u.age >= 25;
});
// [{ name:"Lee", age:30 }]var grouped = users.reduce(function(acc, u) {
if (!acc[u.age]) acc[u.age] = [];
acc[u.age].push(u);
return acc;
}, {});
// {20:[{...}], 30:[{...}]}function unique(arr) {
var result = [];
arr.forEach(function(item) {
if (result.indexOf(item) === -1) {
result.push(item);
}
});
return result;
}
unique([1,2,2,3]); // [1,2,3]ES5에서 배열과 객체를 다루는 메서드는 지금까지도 실무에서 기본 중의 기본입니다.
특히 forEach, map, filter, reduce, Object.keys, Object.defineProperty 등은
코드의 가독성, 재사용성, 안정성을 크게 높여줍니다.
