简体   繁体   中英

Javascript array to string returning in a function

I'm extremely new to coding (only my 2nd day with it) and I've been starting with JavaScript because a website I'm using is helping me and I have learning difficulties I won't go into here but I want to at least try to learn as much as I can:). However, I'm on a challenge on this website and I've been hitting a road block for the past few hours on something I'm sure is obvious but I'm at a frustrated point and hoping some of you kind folks can help. The website is using tests to see if the challenges are passed as per the brief.

I've been able to figure out that I need to use Array.join() on the array parts to satisfy the test individually but I'm blanking on how to do them all/call them as per the challenge instructions.

Challenge info :

Create String The function createString takes an array of strings and should return a string consisting of all the strings in the array with a space in between each one. If the array is empty, it should return an empty string.

createString([]);
// should return ''
createString(['hello', 'world']);
// should return 'hello world'
createString(['my', 'name', 'is', 'frank']);
// should return 'my name is frank'

This is the starting code

function createString (array) {
  // code here
}

This is where I got to before my brain melted from frustration:

function createString (array) {
  let arr1 = [].join(' ');
  let arr2 = ['hello', 'world'].join(' ');
  let arr3 = ['my', 'name', 'is', 'frank'].join(' ');
  return array;
}

createString();

I fully intend to brush up more of the basics but seeing where I'm going wrong with this would help a lot. I think I have to call the function in a way that gives it the right part of the array?

Please help

Few observations as per your current implementation :

function createString (array) {
  let arr1 = [].join(' ');
  let arr2 = ['hello', 'world'].join(' '); --> Using hard coded data. It should be dynamic as per the passed parameter.
  let arr3 = ['my', 'name', 'is', 'frank'].join(' ');
  return array; --> Returning the same parameter value without making any changes in it.
}

createString(); --> Calling a function without passing a parameter to it.

Here you go with the correct implementation :

 function createString (arr) { return arr.join(' '); } const arr1Str = createString([]); const arr2Str = createString(['hello', 'world']); const arr3Str = createString(['my', 'name', 'is', 'frank']); console.log(arr1Str); console.log(arr2Str); console.log(arr3Str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM