0

I have found that in lodash, the array methods also work on strings. For example:

> _.last('abc')
'c'
> _.indexOf('abc', 'x')
-1

Is this a standard behavior, and can this be relied on? The documentation does not say anything about it as far as I know.

Please note that the above methods are just examples. What I am more inclined to know is whether lodash expects its array methods to be used on strings. I need to write production code and I can not rely on something that works but the standard docs have not mentioned or acknowledged or guaranteed.

asked Nov 20, 2016 at 10:35
0

1 Answer 1

3

You can consider a String to essentially be an array of characters. They have certain properties and functions that you'd find on an Array, such as .length and .indexOf().

Based on the lodash source for .last and .indexOf, they use the .length property to determine the last character, or index of a character within an array.

These implementations, while could work with Strings in most scenarios because of their Array-like nature, will not work in all, since lodash uses bracket notation (str[0]) to find the last character/index of an item with an array. This is not universally supported e.g. for IE7, which is why the charAt method exists for accessing a character at a given index for a string.

You can do both of these things natively:

var str = 'mystring';
str.charAt(str.length - 1); // 'g'
var str = 'mystring';
str.indexOf('y') // 1`
answered Nov 20, 2016 at 10:52
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.