无法在函数中返回值/变量

时间:2018-11-04 09:36:21

标签: javascript arrays loops for-loop multidimensional-array

当我console.log时,它将所有数组显示为字符串,因为在我的数组中,它们是多维的;在使用console.log in函数的代码下面看,没有返回但未定义

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))

如果我使用return,它只打印一行;

选中此

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))

newArr变量是数组多维 看起来像这样;

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

在这种情况下,我尝试使用for循环,因为我想训练自己的逻辑;),有人可以帮助我找出问题所在吗?或解决此问题? 谢谢

2 个答案:

答案 0 :(得分:1)

该函数在循环的第一次迭代之后返回。这样会阻止其余的迭代执行。您必须从函数返回一个数组。您可以将所有项目push()放入循环内的数组,然后返回该数组:

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))

答案 1 :(得分:0)

问题是public class AverageDriver { public static void main(String[] args) { Average MyScores = new Average(); System.out.print(MyScores); } } 语句立即结束了整个循环(与return相同)。如果要结束循环,则不能直接返回。另一方面,您可以有目的地使用它来结束循环,例如,如果找到了所需的项目并且不再需要循环了。

如何实际使用return in loop:

break

很抱歉使用ES6,太懒了,无法编写旧的JS。