So I am just messing around with functions and creating my own to make sure I understand concepts better. I wrote out this one below and it seems to be almost there, however I have one issue.
function strAdd() {
let strResult = '';
let numResult = 0;
for (let i=0; i < arguments.length; i ) {
if (typeof arguments[i] === 'string') {
let args = Array.prototype.slice.call(arguments[i])
strResult = args.join("");
} else if (typeof arguments[i] === 'number') {
numResult = arguments[i];
}
}
return console.log(`this string says ${strResult} and the numbers add up to ${numResult}`);
}
When ever I print out the the strings, they are still being logged out as one string as opposed to separate strings so
strAdd('here', 10, 'are', 10, 2, 'the', 35, 'strings')
Gives me
this string says herearethestrings and the numbers add up to 57
Whenever I try adding different chars into the join method, all it does is separates the chars within each string by the specified char and not the string itself. So
strResult = args.join(" ");
would give me
this string says h e r ea r et h es t r i n g s and the numbers add up to 57
instead of splitting up the chars. I notice how the strings are still being joined too. Any thoughts on how I can refactor this code?
CodePudding user response:
If you wish for output such as "here are the strings" (and even if not) you should understand the different parameters. Arrays and Strings have a lot in common but they are different types. When you split
or convert to array (slice
) or join
you might change from one type to another. But no worries. you can always join("")
or split("")
to swap from one to another.
function strAdd() {
var arr_string_arguments = []
let numResult = 0;
for (let i = 0; i < arguments.length; i ) {
if (typeof arguments[i] === 'string') {
var str = arguments[i]
arr_string_arguments.push(str)
} else if (typeof arguments[i] === 'number') {
numResult = arguments[i];
}
}
var strResult = arr_string_arguments.join(" ");
return console.log(`this string says "${strResult}" and the numbers add up to ${numResult}`);
}
strAdd('here', 10, 'are', 10, 2, 'the', 35, 'strings')