简体   繁体   中英

When looping through an array I wish to push the elements to a new array. That array however remains empty

When I run this loop it takes in an array which contains eight numbers, it loops through and simply pushes them to a global array which is named results. For some reason when I console.log this array outside of the loop it returns 0 []. I wish it to return the eight numbers from the other array.

 const results = [] const validate = arr => { for(let i = 0; i < arr.length; i++){ results.push(arr[i]) } } console.log(results)

That is because you have to run the function validate, now you are just printing results[] which has no items.

validate(arr);

 const results = [] const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const validate = arr => { for (let i = 0; i < arr.length; i++) { results.push(arr[i]) } } validate(arr); console.log(results);

But if you want to make a copy, you can just use:

 const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const results = [...arr]; console.log(results);

What you have done here is simply define a function that copies the contents of the array that has been passed into it. You need to call the function validate with the appropriate value.

 const results = [] const validate = arr => { for(let i = 0; i < arr.length; i++){ results.push(arr[i]) } } validate([1,2,3,4,5,6,7,8]); console.log(results);

You missed calling the function.

 const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const result = []; arr.map((num) => result.push(num)); console.log(result);

const results = [] const validate = (arr) => { console.log(arr) arr.forEach((value)=>{ results.push(value) }); } validate([1,2,3,4,5,6,7,8]); console.log(results);

Your code would work if you included the original array of numbers and you call the function that iterates over it:

 let arr = [1,2,3,4,5,6,7,8]; let results = []; function validate() { for(let i = 0; i < arr.length; i++){ results.push(arr[i]) } } validate(); console.log(results)

But, the Array.prototype.map() method was designed to do just this type of thing:

 let arr = [2,4,6,8]; let results = arr.map(function(element){ return element; // Returns item to resulting array }); console.log(results)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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