Typescript 맵 반복
타이프 스크립트 맵을 반복하려고하는데 오류가 계속 발생하고 사소한 문제에 대한 해결책을 아직 찾을 수 없습니다.
내 코드는 다음과 같습니다.
myMap : Map<string, boolean>;
for(let key of myMap.keys()) {
console.log(key);
}
그리고 오류가 발생합니다.
'IterableIteratorShim <[string, boolean]>'유형은 배열 유형 또는 문자열 유형이 아닙니다.
전체 스택 추적 :
Error: Typescript found the following errors:
/home/project/tmp/broccoli_type_script_compiler-input_base_path-q4GtzHgb.tmp/0/src/app/project/project-data.service.ts (21, 20): Type 'IterableIteratorShim<[string, boolean]>' is not an array type or a string type.
at BroccoliTypeScriptCompiler._doIncrementalBuild (/home/project/node_modules/angular-cli/lib/broccoli/broccoli-typescript.js:115:19)
at BroccoliTypeScriptCompiler.build (/home/project/node_modules/angular-cli/lib/broccoli/broccoli-typescript.js:43:10)
at /home/project/node_modules/broccoli-caching-writer/index.js:152:21
at lib$rsvp$$internal$$tryCatch (/home/project/node_modules/rsvp/dist/rsvp.js:1036:16)
at lib$rsvp$$internal$$invokeCallback (/home/project/node_modules/rsvp/dist/rsvp.js:1048:17)
at lib$rsvp$$internal$$publish (/home/project/node_modules/rsvp/dist/rsvp.js:1019:11)
at lib$rsvp$asap$$flush (/home/project/node_modules/rsvp/dist/rsvp.js:1198:9)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
angular-cli beta5 및 typescript 1.8.10을 사용하고 있으며 목표는 es5입니다. 누구든지이 문제가 있었습니까?
Map.prototype.forEach((value, key, map) => void, thisArg?) : void
대신 사용할 수 있습니다.
다음과 같이 사용하십시오.
myMap.forEach((value: boolean, key: string) => {
console.log(key, value);
});
Array.from () 메서드를 사용하여 Array로 변환하십시오.
myMap : Map<string, boolean>;
for(let key of Array.from( myMap.keys()) ) {
console.log(key);
}
사용 Array.from , Array.prototype.forEach을 () 하고, 기능을 화살표 :
키를 반복 합니다 .
Array.from(myMap.keys()).forEach(key => console.log(key));
값을 반복 합니다 .
Array.from(myMap.values()).forEach(value => console.log(value));
항목을 반복 합니다 .
Array.from(myMap.entries()).forEach(entry => console.log('Key: ' + entry[0] + ' Value: ' + entry[1]));
This worked for me. TypeScript Version: 2.8.3
for (const [key, value] of Object.entries(myMap)) {
console.log(key, value);
}
Per the TypeScript 2.3 release notes on "New --downlevelIteration
":
for..of statements
, Array Destructuring, and Spread elements in Array, Call, and New expressions support Symbol.iterator in ES5/E3 if available when using--downlevelIteration
This is not enabled by default! Add "downlevelIteration": true
to your tsconfig.json
, or pass --downlevelIteration
flag to tsc
, to get full iterator support.
With this in place, you can write for (let keyval of myMap) {...}
and keyval
's type will be automatically inferred.
Why is this turned off by default? According to TypeScript contributor @aluanhaddad,
It is optional because it has a very significant impact on the size of generated code, and potentially on performance, for all uses of iterables (including arrays).
If you can target ES2015 ("target": "es2015"
in tsconfig.json
or tsc --target ES2015
) or later, enabling downlevelIteration
is a no-brainer, but if you're targeting ES5/ES3, you might benchmark to ensure iterator support doesn't impact performance (if it does, you might be better off with Array.from
conversion or forEach
or some other workaround).
es5
for (let entry of Array.from(map.entries())) {
let key = entry[0];
let value = entry[1];
}
es6
for (let [key, value] of map) {
console.log(key, value);
}
I'm using latest TS and node (v2.6 and v8.9 respectively) and I can do:
let myMap = new Map<string, boolean>();
myMap.set("a", true);
for (let [k, v] of myMap) {
console.log(k + "=" + v);
}
This worked for me.
Object.keys(myMap).map( key => {
console.log("key: " + key);
console.log("value: " + myMap[key]);
});
Just simple explanation to do it from HTML if you have a Map of types (key, array):
I initialize the array this way:
public cityShop: Map<string, Shop[]> = new Map();
And for iterate over it, I create an array from key values: - just use it as an array with : keys = Array.from(this.cityShop.keys());
Then, in HTML, I can use:
*ngFor="let key of keys"
Inside this bucle, I just get the array value with this.cityShop.get(key)
And... done!
If you don't really like nested functions, you can also iterate over the keys:
myMap : Map<string, boolean>;
for(let key of myMap) {
if (myMap.hasOwnProperty(key)) {
console.log(JSON.stringify({key: key, value: myMap[key]}));
}
}
Note, you have to filter out the non-key iterations with the hasOwnProperty
, if you don't do this, you get a warning or an error.
참고URL : https://stackoverflow.com/questions/37699320/iterating-over-typescript-map
'Programing' 카테고리의 다른 글
PHP를 사용하여 mysql 테이블에 타임 스탬프 저장 (0) | 2020.09.08 |
---|---|
HTML5 동영상에 미리보기 이미지를 설정하는 방법은 무엇입니까? (0) | 2020.09.08 |
작업 디렉토리에 숨김을 적용 할 수없는 이유는 무엇입니까? (0) | 2020.09.08 |
각 경우에 값 범위와 함께 switch 문을 사용합니까? (0) | 2020.09.08 |
PHP에서 MySQL 테이블의 마지막으로 삽입 된 ID를 얻으려면 어떻게해야합니까? (0) | 2020.09.08 |