0

I've got an API that can return either a short Array[String] or a String itself. This is being returned by Angular's $http.get. I would like to return this as a String.

Is it safe to assume that calling the .toString() method on either an Array or String will not give me grief?

Example via browser console:

"something".toString();
"something"
["something"].toString();
"something"

Thanks!

3
  • I think its not a problem. If the array has more strings then you will get a single string comma separated. Make sure the array size is always 1. If not, check for type, then if it is an array, pick the first element. Commented Nov 3, 2015 at 19:42
  • What happens if the array contains more than one element? Commented Nov 3, 2015 at 19:42
  • @BillF. A single string containing all the array values comma separated will be returned. Reference: Array.prototype.toString()... Commented Nov 3, 2015 at 19:44

2 Answers 2

3

Is it possible API would return Array[String1, String2] or Array[] (empty array)? I'd better write more explicit code:

var apiMessage = Array.isArray(message) ? message[0] : message;
Sign up to request clarification or add additional context in comments.

1 Comment

This is pretty much what I was looking for!
1

Safe depends on your trust to your back-end. And that's why:

["something", null, undefined, {}].toString() => "something,,[object Object]"

2 Comments

The devil is always in the details.
If only you develop back by your self, so you can not fool yourself :D

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.