简体   繁体   English

在Javascript中迭代数组

[英]Iterating over Arrays in Javascript

I am a JavaScript newbie. 我是一个JavaScript新手。 I'm trying to practice some sample JavaScript problems. 我正在尝试一些示例JavaScript问题。 I'm a little stuck when it comes to this question about iterating over arrays. 关于迭代数组的问题,我有点卡住了。 Can anyone point me in the right direction? 谁能指出我正确的方向?

I am trying to take the values in oldArray , add 5 to each of them, and store in newArray . 我试图获取oldArray的值,为每个值添加5,并存储在newArray

var oldArray = [12, 45, 6, 23, 19, 20, 20, 15, 30, 42];

var newArray = [];

function plusFive(oldArray[i]) {

    for (var i = 0; i < oldArray.length; i++) {
        newArray.push(oldArray[i]) + 5) };
    }
}

Bug in your code is an additional parenthesis and closing brace in push statement line, just remove them. 代码中的错误是push语句行中的附加括号和右括号,只需删除它们即可。 Also there is no need to set function parameter here since both array are accessible inside the function, if you want to pass then you need to change it to function plusFive(oldArray) , and call the function with array as parameter. 此外,不需要在此处设置函数参数,因为两个数组都可以在函数内部访问,如果要传递,则需要将其更改为function plusFive(oldArray) ,并使用数组作为参数调用函数。

newArray.push(oldArray[i] + 5) ;
//-----------------------^----^-

Working snippet : 工作片段:

 var newArray = []; function plusFive(oldArray) { for (var i = 0; i < oldArray.length; i++) { newArray.push(oldArray[i] + 5) }; } plusFive([1,2,4,6,32,44]); document.write( 'New array :' + '<pre>' + JSON.stringify(newArray) + '</pre>' ); 


Function without array as parameter 没有数组作为参数的函数

 var oldArray = [12, 45, 6, 23, 19, 20, 20, 15, 30, 42]; var newArray = []; function plusFive() { for (var i = 0; i < oldArray.length; i++) { newArray.push(oldArray[i] + 5) }; } plusFive(); document.write( 'Old array :' + '<pre>' + JSON.stringify(oldArray) + '</pre>' + 'New array :' + '<pre>' + JSON.stringify(newArray) + '</pre>' ); 


But it's better to use map() for creating a modified array from an existing array 但最好使用map()从现有数组创建修改后的数组

 var oldArray = [12, 45, 6, 23, 19, 20, 20, 15, 30, 42]; var newArray = oldArray.map(function(v) { return v + 5; }); document.write( 'Old array :' + '<pre>' + JSON.stringify(oldArray) + '</pre>' + 'New array :' + '<pre>' + JSON.stringify(newArray) + '</pre>' ); 

Your code is almost right, but you closed parenthesises incorrectly, and you need to name the function argument correctly. 您的代码几乎是正确的,但您错误地关闭了括号,并且您需要正确命名函数参数。 For function arguments, you're just giving labels. 对于函数参数,您只是给出标签。 You can't name a variable something[a] , and an argument cannot be named something[a] . 你不能将变量命名something[a] ,而参数不能被命名为 something[a]

Try: 尝试:

var oldArray = [12, 45, 6, 23, 19, 20, 20, 15, 30, 42];

var newArray = [];

function plusFive(oldArray) {
    for (var i = 0; i < oldArray.length; i++) {
        newArray.push(oldArray[i] + 5)
    }
}

plusFive();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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