简体   繁体   中英

How to 'double' numbers in an array, and save it in a new array

This is a 2 step problem:

1.) I am trying to 'double' the contents of one array (original Array), save it in a new array (Doubled Array).

2.) Then assign those two arrays to an Object with 2 attributes. New Object Orginal Numbers Doubled Numbers

This is what I have so far, what am I doing wrong?

var numbers = [8, 12, 5, 2, 5, 7];
var doubledNumbers = [];


function doubled(arr){
 for (var i = 0; i < arr.length; i ++){
  var dub = arr[i];
   var dubb = dub*2;
   doubledNumbers.push(dubb);
 }

}

var collectionNumbers = {
  orginialNumbers: numbers,
  doubledNumbers: doubled(numbers)
};

console.log(collectionNumbers);

The best way to do this in Javascript is using the map function:

var doubledNumbers = numbers.map(n => n*2);

The argument to map is the function that it uses to transform the elements in the first array into the elements in the second array. It is a tremendously useful method.

To answer your original question, the reason you were seeing undefined in collectionNumbers is because you forgot to return doubledNumbers in your function (and functions by default return undefined .

var numbers = [8, 12, 5, 2, 5, 7];
var doubledNumbers = [];


function doubled(arr){
 var doubledNumbers = [];
 for (var i = 0; i < arr.length; i ++){
  var dub = arr[i];
   var dubb = dub*2;
   doubledNumbers.push(dubb);
 }
 return doubledNumbers;

}

var collectionNumbers = {
  orginialNumbers: numbers,
  doubledNumbers: doubled(numbers)
};

console.log(collectionNumbers);

Your whole routine can be simplified to

var numbers = [8, 12, 5, 2, 5, 7];
var collectionNumbers = {
  orginialNumbers: numbers,
  doubledNumbers: numbers.map(function(n) { return n*2; })
};

console.log(collectionNumbers);

using Array.map to create a new array with the doubled numbers

What's wrong with your current code, is that your doubled function is returning nothing (which means it's returning undefined ).

A better function would look like this:

function doubled (arr) {
    var doubled = [];
    for (var i = 0; i < arr.length; i++) {
        doubled.push(arr[i] * 2);
    }
    return doubled;
}

However, an even better solution would be to just do this:

var collectionNumbers = {
    orginialNumbers: numbers,
    doubledNumbers: numbers.map(function (n) { return n * 2; })
};

.map is awesome.

using Array.from , you can double and return new array

  let inputArray = [9,8,7,3,2] let outputArray = Array.from(inputArray, x => x *2) // creates new array console.log(outputArray) 

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