can't return value/variable in a function

1671 views javascript
4

when I console.log it display all the arrays to be the string, because in my arrays, they are multi-dimensions; look below the code using console.log in function, without return but undefined

function changeStrings(arr, replacement) {
    var newArr = []

  for ( var i = 0 ; i < arr.length ; i++) {
    newArr.push(arr[i].split(" "))
  }

  for ( var j = 0 ; j < replacement.length ; j++ ) {
    newArr[0][3] = replacement[j-2]
    newArr[1][3] = replacement[j-1]
    newArr[2][4] = replacement[j]
  }
   
  for ( var k = 0 ; k < newArr.length ; k++ ) {
    console.log(newArr[k].join(" "))
  }
 
};


let initial = ["my city in London", "my name is Mike", "my phone number is 00909090"];
let replacements = ['Paris', 'John', '1234'];

console.log(changeStrings(initial, replacements))

and if i using return , it just print one line;

check this

function changeStrings(arr, replacement) {
    var newArr = []

  for ( var i = 0 ; i < arr.length ; i++) {
    newArr.push(arr[i].split(" "))
  }

  for ( var j = 0 ; j < replacement.length ; j++ ) {
    newArr[0][3] = replacement[j-2]
    newArr[1][3] = replacement[j-1]
    newArr[2][4] = replacement[j]
  }
   
  for ( var k = 0 ; k < newArr.length ; k++ ) {
    var dispplay = newArr[k].join(" ")
    return dispplay
  }
 
};

// now let's test out our functions!
let initial = ["my city in London", "my name is Mike", "my phone number is 00909090"];
let replacements = ['Paris', 'John', '1234'];

console.log(changeStrings(initial, replacements))

the newArr variable is array multidimension it looks like this ;

[ [ 'my', 'city', 'in', 'Paris' ],
  [ 'my', 'name', 'is', 'John' ],
  [ 'my', 'phone', 'number', 'is', '1234' ] ]

i am trying to using for loop for this case, because i want to train my logic;), can anyone help me to find out what's wrong ? or fix this ? thank you

answered question

1 Answer

0

You have to return an array from the function. You can push() all the item to the array inside the loop then return the array:

function changeStrings(arr, replacement) {
  var newArr = []

  for ( var i = 0 ; i < arr.length ; i++) {
    newArr.push(arr[i].split(" "))
  }

  for ( var j = 0 ; j < replacement.length ; j++ ) {
    newArr[0][3] = replacement[j-2]
    newArr[1][3] = replacement[j-1]
    newArr[2][4] = replacement[j]
  }
  var display = [];
  for ( var k = 0 ; k < newArr.length ; k++ ) {
    display.push(newArr[k].join(" "));
  }
 
  return display
};

// now let's test out our functions!
let initial = ["my city in London", "my name is Mike", "my phone number is 00909090"];
let replacements = ['Paris', 'John', '1234'];

console.log(changeStrings(initial, replacements))

posted this

Have an answer?

JD

Please login first before posting an answer.