8

I'm trying a simple string split in NodeJS, but it is returning an object, not array.

var mytext = "a,b,c,d,e,f,g,h,i,j,k";
var arr = mytext.split(",");
console.log(typeof mytext); <======= output string
console.log(typeof arr);    <======= output object

jsfiddle: http://jsfiddle.net/f4NnQ/

why?

2
  • 5
    in js array is an object Commented Apr 1, 2014 at 13:05
  • I've been amazed on this.. I have a string, splitting using \r\n, and somehow it becomes an object. I'm using the clipboard onpaste to grab the string, but definitely can't understand what it's doing.. When I use control.log, it appears as an array.. Even tried JSON.parse(JSON.stringify(s)) to switch, but still an object. All I can say is use push() and pop() to work with it.. Hopefully I can figure this one out.... Commented Apr 29, 2021 at 14:19

6 Answers 6

14

The output of String.prototype.split is an Array and that is an Object.

console.log(typeof []);
// object

You can confirm that the returned object is an array, like this

console.log(Object.prototype.toString.call(arr));
// [object Array]
console.log(arr);
// [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k' ]

Quoting from the MDN Documentation of String.prototype.split,

The split() method splits a String object into an array of strings by separating the string into substrings.

Sign up to request clarification or add additional context in comments.

1 Comment

I did this, but console.log(typeof arr) gives "string" not "array", did I miss something?
2

Arrays are objects in javascript.

If you want to check if its an array -

you can do -

Array.isArray(arr)

Comments

1

Split method always returns an array . Array is an object in javascript. If you want to check whether it is an array use Array.isArray(arr)

Comments

0

An array is an object.

Read about typeof results here

Comments

0

If you output as

console.log(arr);

You will see an array

Comments

0
var mytext = "a,b,c,d,e,f,g,h,i,j,k";
var arr = mytext.split(",");
console.log(typeof mytext); <======= output string
console.log(arr);    `this will return object`
for(i=0;i<=10; i++){
console.log(arr[i]);    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.