对于循环和2个数组

时间:2018-06-18 01:58:56

标签: javascript arrays loops for-loop concat

我正在学习Javascript,我对于循环感到困惑。我不知道如何遍历2个数组并从连接在一起的每个数组中打印一个值。我尝试解决下面的问题,但它不起作用。什么是解决这个问题的最佳方法。谢谢你的帮助!

var nums = [1, 5, 88, 2, 5, 42, 57, 101]
var nouns = ["ducks", "telephone booth", "the enterprise", "robots", "amazon", "eraser", "zafod", "a"]

// output of the first function should be: "1 ducks"
for (let i=0; i.nums.length; i++)
    console.log(nums[i].concat(nouns[i]));

2 个答案:

答案 0 :(得分:3)

对于循环条件

您的for循环条件导致错误。 syntax of a for loop表示第二项(“循环条件”)应该计算为布尔值(true / false),该值告诉您何时继续迭代以及何时停止。

现在您有“i.nums.length”作为循环条件,这不是有效代码(因为存储在变量i中的数字没有属性nums) 。

相反,您应该将i < nums.length作为循环条件,true直到i不再是nums数组中的有效索引,此时它是false并且循环停止。

连接输出

数字没有“concat”方法,因此您无法执行nums[i].concat()。要在javascript中将数字与字符串连接起来,可以使用+,它将数字转换为字符串并将其连接到字符串。如果你想要一个空格,你也可以连接它。

检查长度

如果nouns.length小于nums.length,Javascript将为undefined的缺失项生成nouns,但不会抛出错误。要在迭代它们之前确保两个数组的长度相同,如果长度不完全匹配,则可以使用console.assert(nouns.length === nums.length, message)打印错误消息。这不是严格要求的(因为长度在您的示例代码中匹配)但是使代码对于数组声明中的错误更加健壮。

最终代码

最终代码(包含所有修改)如下所示:

var nums = [1, 5, 88, 2, 5, 42, 57, 101];
var nouns = ["ducks", "telephone booth", "the enterprise", "robots", "amazon", "eraser", "zafod", "a"];
console.assert(nums.length === nouns.length, `Array sizes ${nums.length} and ${nouns.length} don't match`);

// output of the first function should be: "1 ducks"
for (let i = 0; i < nums.length; i++) {
    console.log(nums[i] + " " + nouns[i]);
}

答案 1 :(得分:1)

您的代码中存在多个错误。

i.nums.length应为i < nums.length

concat仅适用于字符串,因此首先需要将nums[i]值转换为字符串,然后使用str1.concat(str2)或者您可以在{{1}之间简单地使用+nums[i]这样的方法比较简单:nouns[i]

下面是工作代码,看看:

nums[i] + " " + nouns[i]