如何在javascript中将两个数组传递给函数

如何在javascript中将两个数组传递给函数,javascript,Javascript,我想对wordList数组和wordCount数组进行排序。它们是parralel数组,我想根据每个单词的计数对其进行排序。我不能使用它的内置排序函数,所以我需要编写一个。但我不知道为什么我的代码失败: wordList = ["apple", "have", "pear", "here"]; wordCount = [3, 1, 3, 5]; sortWords(wordList, wordCount); function sortWords(arr1, arr2) { ..... } 我

我想对wordList数组和wordCount数组进行排序。它们是parralel数组,我想根据每个单词的计数对其进行排序。我不能使用它的内置排序函数,所以我需要编写一个。但我不知道为什么我的代码失败:

wordList = ["apple", "have", "pear", "here"];
wordCount = [3, 1, 3, 5];
sortWords(wordList, wordCount);
function sortWords(arr1, arr2) {
 .....
}

我的代码是否成功地将这两个数组传递给函数?

是。。它起作用了。。您应该使用
var
let
初始化变量

function sortWords(arr1, arr2) {
   alert(arr1.length + arr2.length); // gives 8 it works!
}

var wordList = ["apple", "have", "pear", "here"];
var wordCount = [3, 1, 3, 5];
sortWords(wordList, wordCount);

我想你想要的是:

wordList.sort(function(a, b){
  return b.length - a.length;
}

这将在一个简单的步骤中将单词列表从最长的单词排序到最短的单词。

您正在将数组正确地传递给函数。想测试一下吗

var wordList = ["apple", "have", "pear", "here"],
    wordCount = [3, 1, 3, 5];

sortWords(wordList, wordCount);

function sortWords(arr1, arr2) {
  for(fruits in arr1){
      console.log(arr1[fruits]);
  }
  for(numbers in arr2){
    console.log(arr2[numbers]);
  }
}
注意

  • 始终在使用变量之前初始化变量,以避免与有关的任何问题
  • 查看浏览器控制台,查看上述测试的输出

  • 有问题吗?请随时在下面的评论中提问。

    “我的代码是否成功地将这两个数组传递给函数?”是的。如果它不工作,请将函数移到代码其余部分之上。它是如何失败的?您会遇到什么错误?您知道如何调试吗?console.log()是您的朋友。谢谢大家!对初学者真的很有帮助。