Why does this function return Object and not array?

Asked

Viewed 159 times

0

I needed to convert the string into a list/array, did the following function:

function s_for_l(s){var string = new Array(); for (let i of s) {string.push(i)}; return string}

but she only returns object, nay array as expected.

  • Shows the return example, which here only returns that function

  • It’s true what @Maniero said. Only then the values are in array

2 answers

3


The fact that you wait does not mean that it should happen. The expected for me that I read the language specification is to return object even.

See the list of types that Javascript has. Where is the array? Do not result in a type that does not exist. So if it is not a numeric type, text or a special symbol it can only be a object.

The guys object may have specializations, one of these already existing specializations is the array, but this is not the type of the value or variable at that time. A array in JS is only an object as a specific form, for example it has a property lenght to determine how many elements it has within that object. And it has other methods that do specific operations for these specializations of object which we call array.

But kind of Array, exists only in other languages, usually of static typing.

The problem isn’t in that code if you catch the type of one array normally written the type will also be object.

console.log(typeof [1, 2, 3]);

I put in the Github for future reference.

0

Taking advantage of my colleague’s reply Maniero, its function already returns a array, but the type of the returned variable is object

function s_for_l(s){
    var string = new Array(); 
    for (let i of s) string.push(i)
    return string
}

Return data:

Valor

 console.log(convert('Carlos'));

 [ 'C', 'a', 'r', 'l', 'o', 's' ]

Type

console.log(typeof convert('Carlos'));
object

See example

function convert (s) {
    const string = new Array()
    for(let i of s) string.push(i)
    return string
} 

console.log('Valor',convert('Carlos'));
console.log('Tipo',typeof convert('Carlos'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.