entries, fromEntries, from

00_8_3·2021년 5월 26일
0

Obejct.entries

for ... in과 비슷.


const object1 = {
  a: 'somestring',
  b: 42
};
console.log(Object.entries(object1));
// Array [Array ["a", "somestring"], Array ["b", 42]]

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

Obejct.fromEntries

키-값 쌍의 목록을 객체로 바꾼다.

const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);

const obj = Object.fromEntries(entries);

console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }

console.log(entries);

console.log(obj);

console.log(Object.entries(obj));


//1
Map(2) {"foo" => "bar", "baz" => 42}
[[Entries]]
0: {"foo" => "bar"}
1: {"baz" => 42}
size: (...)
__proto__: Map
   
//2
{foo: "bar", baz: 42}
baz: 42
foo: "bar"
__proto__: Object

//2
(2) [Array(2), Array(2)]
0: (2) ["foo", "bar"]
1: (2) ["baz", 42]
length: 2
__proto__: Array(0)

.entries와 .fromEntries

Obejct.from

유사 배열 객체나 반복 가능한 객체를 얕게 복사해
새로운 배열 객체를 만든다.


//문자열에서 배열 만들기
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]


//Set에서 배열만들기
const s = new Set(['foo', window]);
Array.from(s);
// ["foo", window]

//Map에서 배열만들기
const m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m);
// [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];

Array.from(mapper.keys());
// ['1', '2'];

as

//화살표 함수 사용
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]

// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]


// 시퀸스 생성기
const range = (start, stop, step) => Array.from({ length: 5}, (_, i) => start + (i * step) );

console.log(range(0, 4, 1));

추가

Object.slice

function func1(a, b, c) {
  console.log(arguments);
var args = Array.prototype.slice.call(arguments); //또는 [].slice.call(arguments)
  console.log(args);
}
func1(1, 2, 3);

// expected output: Array [1, 2, 3]

0개의 댓글