考虑以下代码:
const map1 = Immutable.Map({a:1, b:2, c:3});
const myMap = map1.map((elem, index) => {
return "Hello " + elem;
})
console.log(myMap.toJS());
// prnts {a: "Hello 1", b: "Hello 2", c: "Hello 3"}
我希望输出为['Hello1', 'Hello2, 'Hello3']
,但是map
也给了我一个带有键的对象。为什么我不能像正常的JavaScript map
那样获得数组作为输出?达到预期结果的最佳方法是什么? (我可以使用forEach
而不是map
,并将每次迭代的结果推送到数组中,但我正在寻找一种更好的方法。)
答案 0 :(得分:1)
使用toArray()代替toJS():
const map1 = Immutable.Map({a:1, b:2, c:3});
const myMap = map1.map((elem, index) => {
return "Hello " + elem;
})
console.log(myMap.toArray());
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>
答案 1 :(得分:0)
您只需使用myMap.keys
就可以得到数组。Array.from(myMap.keys());
可运行的代码段如下:
const map1 = Immutable.Map({a:1, b:2, c:3});
const myMap = map1.map((elem, index) => {
return "Hello " + elem;
})
console.log(Array.from(myMap.keys()));
答案 2 :(得分:0)
只需使用reduce提供不同的口味
const map1 = Immutable.Map({a:1, b:2, c:3});
const myMap = map1.reduce((accumulator, value) => {
accumulator.push("Hello" + value);
return accumulator;
}, [])
console.log(myMap);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>