Array.from

2 0 0
                                        

Iterable - they are objects that implements the Symbol.iterator method within the object body. You can use the for..of in this iterable objects.

Array-likes - they are objects that are similar to an array where in if you iterate, you have to use the indexes and the length.

Note: String is both iterable and array-likes.

================

let name1 = "Croc!";

let greet1 = {

     0: "H",

     1: "i",

     2: "!"

}

function displayTheMessage(){

     for(let x of name1){

         document.writeln(x);

     }

    for(let x in greet1){

        document.writeln(greet1[x]);

    }

}

================

HTML:

displayTheMessage()

Result:

C r o c ! H i !

Note: You can use the for..of in the string since it is iterable. But in the second object, you cannot use the for..of though you can use the for..in.


Array.from - converts the iterables or array-like object to real array. mapFn and thisArg is optional.

syntax:

Array.from(obj, [, mapFn, thisArg])

===============

let name1 = "Croc!";

let greet1 = {

    0: "H",

    1: "i",

    2: "!"

}

function displayTheMessage(){

    let array1 = Array.from(name1);

    let array2 = Array.from(greet1);

    document.writeln(array1);

    document.writeln(array2);

}

===============

HTML:

displayTheMessage()

Result:

C,r,o,c,!

Note: It seems that it is not working in array-like.

Javascript ProgrammingWhere stories live. Discover now