Array comprehension을 알아보자
ECMA6
ECMA5
[{name: "pie", price: 10}, {name: "coffee", price: 5}].map( v=> v.price );
[{name: "pie", price: 10}, {name: "coffee", price: 5}].map(
function(v) {
return v.price;
});
[ 10, 5 ]
Result
v.price for v in [{name: "pie", price: 10}, {name: "coffee", price: 5}]
# or
for v in [{name: "pie", price: 10}, {name: "coffee", price: 5}]
v.price
[ 10, 5 ]
Result
v.price<10
가격이 10 미만인 것만
ECMA6
ECMA5
[{name: "pie", price:10}, {name: "coffee", price: 5}].filter(
v => v.price < 10 ).map( v=> v.price );
[{ name: "pie", price: 10 }, { name: "coffee", price: 5 }].filter(function (v) {
return v.price < 10;
}).map(function (v) {
return v.price;
});
[ 5 ]
Result
v.price for v in [
{name: "pie", price: 10 },{name: "coffee", price: 5 }
] when v.price < 10
[ 5 ]
Result
var i, len, ref, results, v;
ref = [
{
name: "pie",
price: 10
}, {
name: "coffee",
price: 5
}
];
results = [];
for (i = 0, len = ref.length; i < len; i++) {
v = ref[i];
if (v.price < 10) {
results.push(v.price);
}
}
v.price for v in [
{name: "pie", price: 10 },{name: "coffee", price: 5 }
] when v.price < 10
Faster & Memory -Optimized
javascript
var fruits = "apple_12\n"+"banana_34\n"+"coconut_56"
var regexp = /[a-z]+_([0-9]+)/g
> regexp.exec(fruits)
["apple_12", "12"]
> regexp.exec(fruits)
["banana_34", "34"]
> regexp.exec(fruits)
["coconut_56", "56"]
> regexp.exec(fruits)
null
var getNumber = function() {
var result = [];
while (t=regexp.exec(fruits)) {
result.push(t[1]);
}
return result;
};
> getNumber();
[ '12', '34', '56' ]
> fruits = "apple_12\nbanana_34\ncoconut_56"
> regexp = /[a-z]+_([0-9]+)/g
> x[1] while x=regexp.exec fruits
[ '12', '34', '56' ]
> fruits = "apple_12\nbanana_34\ncoconut_56"
> regexp = /[a-z]+_([0-9]+)/g
> x[1] while x=regexp.exec fruits when x[1]<50
[ '12', '34' ]