Underscore #1

GunWยท2019๋…„ 5์›” 3์ผ
1
post-custom-banner

๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป UnderScore

ํ›„๋ฐ˜ ๊ณผ์ œ๋ฅผ ์œ„ํ•ด์„œ๋Š” underscore.js์ฒ˜๋Ÿผ underbar๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค...!
๋ฏธ๋ฆฌ๋ฏธ๋ฆฌ ์—ฐ์Šตํ•ด๋‘์ž :)


์„ค์น˜ : npm install underscore

์‚ฌ์šฉ : const _ = require('underscore')

underscore๋ฅผ htmlํŒŒ์ผ์—์„œ script๋กœ ๋ฐ›์•„์„œ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ์ง€๋งŒ..๋ถˆํŽธํ•˜๋‹ˆ๊นŒ...๐Ÿ™…๐Ÿปโ€


Array

_.first(array, [n])

๋ฐฐ์—ด์˜ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ๋ฆฌํ„ด.

const _ = require('underscore'); // Immutable

const numArr = [3,2,1,4,5];
const korArr = ['๊ฐ€','๋‚˜','๋‹ค','๋ผ','๋งˆ'];

console.log(_.first(numArr));    // 1
console.log(_.first(numArr, 3)); // [ 3, 2, 1 ]

_.initial(array, [n])

๋งˆ์ง€๋ง‰ ์š”์†Œ๋ฅผ ์ œ์™ธํ•œ ๋ฐฐ์—ด์„ ๋ฆฌํ„ด

console.log(_.initial(korArr));   // [ '๊ฐ€', '๋‚˜', '๋‹ค', '๋ผ' ]
console.log(_.initial(korArr, 3)) // [ '๊ฐ€', '๋‚˜', '๋‹ค', '๋ผ' ]

_.last(array, [n])

๋งˆ์ง€๋ง‰ ์š”์†Œ๋ฅผ ๋ฆฌํ„ด

console.log(_.last(korArr));     // '๋งˆ'
console.log(_.last(korArr, 3));  // [ '๋‹ค', '๋ผ', '๋งˆ' ]

_.last(array, [n])

๋งˆ์ง€๋ง‰ ์š”์†Œ๋ฅผ ๋ฆฌํ„ด

console.log(_.last(korArr));     // '๋งˆ'
console.log(_.last(korArr, 3));  // [ '๋‹ค', '๋ผ', '๋งˆ' ]

_.rest(array, [index])

index์ดํ›„ ๋ถ€ํ„ฐ ๋ฆฌํ„ด

console.log(_.rest(korArr))      // [ '๋‚˜', '๋‹ค', '๋ผ', '๋งˆ' ]
console.log(_.rest(korArr, 3))   // [ '๋ผ', '๋งˆ' ]

_.flatten(array, [shallow])

์ค‘์ฒฉ ๋ฐฐ์—ด์„ ํ•ด์ œํ•œ๋‹ค.

console.log(_.flatten([1, [2], [3, [[4]]]]));         // [ 1, 2, 3, 4 ]
console.log(_.flatten([1, [2], [3, [[4]]]], true));   // [ 1, 2, 3, [ [ 4 ] ] ]

_.without(array, *values)

values๋ฅผ ์ œ๊ฑฐํ•œ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ๋ฆฌํ„ด

console.log(_.without([1, 2, 1, 0, 3, 1, 4], 0, 1));   // [ 2, 3, 4 ]
console.log(_.without(korArr, '๋‚˜', '๋งˆ'));            // [ '๊ฐ€', '๋‹ค', '๋ผ' ]

_.union(*arrays)

ํ•ฉ์ง‘ํ•ฉ

console.log(_.union([1, 2, 3], [101, 2, 1, 10], [2, 1])); // [ 1, 2, 3, 101, 10 ]

_.intersection(*arrays)

๊ต์ง‘ํ•ฉ

console.log(_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1])); // [ 1, 2 ]

_.difference(array, *others)

์ฐจ์ง‘ํ•ฉ

console.log(_.difference([1, 2, 3, 4, 5], [5, 2, 10])); // [ 1, 3, 4 ]

_.indexOf(array, value, [isSorted])

๋ฐฐ์—ด์—์„œ value๋ฅผ ์ฐพ์•„ index๋ฅผ ๋ฆฌํ„ด

console.log(_.indexOf([1, 2, 3], 2)); // 1

_.range([start], stop, [step])

start~stop๊นŒ์ง€ step๋งŒํผ ๋ฐฐ์—ด ์ƒ์„ฑ

console.log(_.range(0, 10))      // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
console.log(_.range(0, 10, 2))   // [ 0, 2, 4, 6, 8 ]
console.log(_.range(0, -10, -1)) // [ 0, -1, -2, -3, -4, -5, -6, -7, -8, -9 ]
console.log(_.range(0))          // []

profile
ggit
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€