For Of 루프에서 객체 사용
for of 루프에서 객체를 사용할 수없는 이유는 무엇입니까? 아니면 브라우저 버그입니까? 이 코드는 Chrome 42에서 작동하지 않으며 undefined는 함수가 아닙니다.
test = { first: "one"}
for(var item of test) {
console.log(item)
}
for..of 루프 뿐만 아니라 객체, 배열과 같은 반복 가능한 객체를 지원합니다.
객체의 값을 반복하려면 다음을 사용하십시오.
for (var key in test) {
var item = test[key];
}
키-값 저장소에 데이터를 저장하는 경우이 목적을 위해 명시 적으로 설계된 사용하십시오Map .
하지만 객체를 사용해야하는 경우 ES2017 (ES8)에서 다음을 사용할 수 있습니다 Object.values.
const foo = { a: 'foo', z: 'bar', m: 'baz' };
for (let value of Object.values(foo)) {
console.log(value);
}
그는 아직 지원되지 않으면 polyfill을 사용 의 대체 버전을Object.values()
마지막으로이 구문을 지원하지 않는 이전 환경을 지원하는 경우 forEach및 사용에 의존해야합니다 Object.keys.
var obj = { a: 'foo', z: 'bar', m: 'baz' };
Object.keys(obj).forEach(function (prop) {
var value = obj[prop];
console.log(value);
});
다음 구문을 사용할 수 있습니다.
let myObject = {first: "one"};
for(let [key, value] of Object.entries(myObject)) {
console.log(key, value); // "first", "one"
}
하나, Object.entries 현재 지원이 부족합니다IE 또는 iOS Safari에서는 작동하지 않습니다. 아마도 폴리 필이 필요할 것입니다.
ECMAScript 2015 / ES6의 반복자, 반복자 및 for..of 루프
let tempArray = [1,2,3,4,5];
for(element of tempArray) {
console.log(element);
}
// 1
// 2
// 3
// 4
// 5
하지만 우리가
let tempObj = {a:1, b:2, c:3};
for(element of tempObj) {
console.log(element);
}
// error
for..of 루프는 Iterables , 즉 Iterator 프로토콜 을 준수 하는 @@ iterator 가있는 객체 에서만 작동 하기 때문에 오류가 발생 합니다 . 즉, 다음 메서드 가있는 객체가 있어야합니다 . next 메소드는 인수를받지 않으며이 두 속성을 가진 객체를 반환해야합니다.
done : 참일 때 시퀀스가 끝났다는 신호, 거짓은 더 많은 값이있을 수 있음을 의미합니다. value : 시퀀스의 현재 항목입니다.
따라서 for..of 와 함께 작동 하는 객체를 Iterable 로 만들려면 다음을 수행 할 수 있습니다.
1. Symbol.iterator 속성을 통해 신비한 @@ iterator 속성 에 할당 하여 개체를 Iterable 로 만듭니다 . 방법은 다음과 같습니다.
let tempObj = {a:1, b:2, c:3};
tempObj[Symbol.iterator]= () => ({
next: function next () {
return {
done: Object.keys(this).length === 0,
value: Object.keys(this).shift()
}
}
})
for(key in tempObj){
console.log(key)
}
// a
// b
// c
2. Iterable 을 반환하는 Object.entries 를 사용합니다 .
let tempObj = {a:1, b:2, c:3};
for(let [key, value] of Object.entries(tempObj)) {
console.log(key, value);
}
// a 1
// b 2
// c 3
3. Object.keys 사용 , 방법은 다음과 같습니다.
let tempObj = {a:1, b:2, c:3};
for (let key of Object.keys(tempObj)) {
console.log(key);
}
// a
// b
// c
도움이 되었기를 바랍니다!!!!!!
이 코드로 객체를 반복 가능하게 만들었습니다.
Object.prototype[Symbol.iterator] = function*() {
for(let key of Object.keys(this)) {
yield([ key, this[key] ])
} }
용법:
for(let [ key, value ] of {}) { }
대안 :
for(let [ key, value ] of Object.entries({})) { }
객체 리터럴에는 Symbol.iterator 속성 이 없기 때문 입니다. 구체적으로, 당신은 단지 반복 처리를 통해 할 수있는 문자열 , 배열이 , 지도 , 설정 , 인수 , NodeList를이 (널리 지원되지 않음) 및 발전기 때와 ... 대한의 루프.
Object Literal 반복을 처리하기 위해 두 가지 옵션이 있습니다.
...에서
for(let key in obj){
console.log(obj[key]);
}
Object.keys + forEach
Object.keys(obj).forEach(function(key){
console.log(obj[key]);
});
대답은 아니요입니다. For..Of를 Object 리터럴과 함께 사용할 수 없습니다.
For..Of는 이터 러블 전용이라는 Overv에 동의합니다. for..in으로 키와 값을 반복하기 위해 Objects를 사용하기 때문에 똑같은 질문이있었습니다. 그러나 나는 그것이 ES6 MAPS 와 SETS 의 목적이라는 것을 깨달았습니다 .
let test = new Map();
test.set('first', "one");
test.set('second', "two");
for(var item of test) {
console.log(item); // "one" "two"
}
따라서 for..In ( hasOwnProperty으로 유효성 검사 )을 사용할 필요가없고 Object.keys ()를 사용할 필요가 없다는 목표를 달성합니다 .
또한 키는 문자열로 제한되지 않습니다. 숫자, 개체 또는 기타 리터럴을 사용할 수 있습니다.
Object literals don't have built-in iterators, which are required to work with for...of loops. However, if you don't want to go thru the trouble of adding your own [Symbol.iterator] to your object, you can simply use the Object.keys() method. This method returns an Array object, which already has a built-in iterator, so you can use it with a for...of loop like this:
const myObject = {
country: "Canada",
province: "Quebec",
city: "Montreal"
}
for (let i of Object.keys(myObject)) {
console.log("Key:", i, "| Value:", myObject[i]);
}
//Key: country | Value: Canada
//Key: province | Value: Quebec
//Key: city | Value: Montreal
It is possible to define an iterator over any giving object, this way you can put different logic for each object
var x = { a: 1, b: 2, c: 3 }
x[Symbol.iterator] = function* (){
yield 1;
yield 'foo';
yield 'last'
}
Then just directly iterate x
for (let i in x){
console.log(i);
}
//1
//foo
//last
It is possible to do the same thing on the Object.prototype object And have a general iterator for all objects
Object.prototype[Symbol.iterator] = function*() {
for(let key of Object.keys(this)) {
yield key
}
}
then iterate your object like this
var t = {a :'foo', b : 'bar'}
for(let i of t){
console.log(t[i]);
}
Or this way
var it = t[Symbol.iterator](), p;
while(p = it.next().value){
console.log(t[p])
}
I just did the following to easily console out my stuff.
for (let key in obj) {
if(obj.hasOwnProperty(key){
console.log(`${key}: ${obj[key]}`);
}
}
What about using
function* entries(obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}
}
for ([key, value] of entries({a: "1", b: "2"})) {
console.log(key + " " + value);
}
in ES6 you could go with generator:
var obj = {1: 'a', 2: 'b'};
function* entries(obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}
}
let generator = entries(obj);
let step1 = generator.next();
let step2 = generator.next();
let step3 = generator.next();
console.log(JSON.stringify(step1)); // {"value":["1","a"],"done":false}
console.log(JSON.stringify(step2)); // {"value":["2","b"],"done":false}
console.log(JSON.stringify(step3)); // {"done":true}
Here is the jsfiddle. In the output you will get an object with the "value" and "done" keys. "Value" contains everything you want it to have and "done" is current state of the iteration in bool.
Using Array Destruction you can iterate it as follows using forEach
const obj = { a: 5, b: 7, c: 9 };
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});
How about using Object.keys to get an array of keys? And then forEach on the Array?
obj = { a: 1, b:2}
Object.keys(obj).forEach( key => console.log(`${key} => ${obj[key]}`))
참고URL : https://stackoverflow.com/questions/29885220/using-objects-in-for-of-loops
'program story' 카테고리의 다른 글
| IE9-10에서 SVG를 사용한 배경 크기 (0) | 2020.10.23 |
|---|---|
| 피쉬 쉘에서 환경 변수를 설정하는 방법 (0) | 2020.10.23 |
| Python NameError : 'include'이름이 정의되지 않았습니다. (0) | 2020.10.23 |
| OpenCV의 cvWaitKey () 함수는 무엇을합니까? (0) | 2020.10.23 |
| SQL에서 Entity Framework 수 그룹화 기준 (0) | 2020.10.23 |