Iterating over Arrays in Javascript

亡梦爱人 提交于 2021-01-27 06:53:35

问题


I am a JavaScript newbie. I'm trying to practice some sample JavaScript problems. 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.

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

回答1:


Bug in your code is an additional parenthesis and closing brace in push statement line, just remove them. 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.

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

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



回答2:


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].

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


来源:https://stackoverflow.com/questions/33750626/iterating-over-arrays-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!