How to 'double' numbers in an array, and s

2020-03-30 04:55发布

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

5条回答
我只想做你的唯一
2楼-- · 2020-03-30 05:09

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.

查看更多
The star\"
3楼-- · 2020-03-30 05:11

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)    

查看更多
等我变得足够好
4楼-- · 2020-03-30 05:16

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);
查看更多
疯言疯语
5楼-- · 2020-03-30 05:20

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

查看更多
Explosion°爆炸
6楼-- · 2020-03-30 05:21

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.

查看更多
登录 后发表回答