简体   繁体   中英

Map to another class with array.map()

Consider this code:

class myClass {
    constructor(obj) {
        this.content = "mapped to myClass";
    }
}

array = [{content:"first"},{content:"second"}]; 
array.map(o=> {o_mapped = new myClass(); return o_mapped} ); //1*
console.log(JSON.stringify(array));

array = array.map(o=> {o_mapped = new myClass(); return o_mapped} ); //2*
console.log(JSON.stringify(array));

I have this output, and I do not know why 2* does not work like 1*

[{"content":"first"},{"content":"second"}]
[{"content":"mapped to myClass"},{"content":"mapped to myClass"}]

Why this happens? I have used 1* version for simple manipulations with array data and it works

map returns the new array, it doesn't manipulate the original.

*2 works because you reassign array , then print the new array.

If you were using map just to iterate and carry out side effects, like you would when using forEach , then you wouldn't need to reassign the array.

map always return the new array

In this condition your are setting content and then iterating it by map function

    array = [{content:"first"},{content:"second"}]; 
    array.map(o=> {o_mapped = new myClass(); return o_mapped} ); //1*
    console.log(JSON.stringify(array));

In this condition you are using default content and then iterating it by map function

    array = array.map(o=> {o_mapped = new myClass(); return o_mapped} ); //2*
    console.log(JSON.stringify(array));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM