Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

javascript - How to take array of numbers and return array with numbers doubled?

I'm trying to write a function that will take an array of numbers and return an array with those numbers doubled. For example 1, 2, 3 and return should be 2, 4, 6.

This is what I have so far:

const numbers = [1, 2, 3];

function doubleNumbers(numbers) {
    return numbers =  1 * 2 + ", " + 2 * 2 + ", " + 3 * 2;
}

console.log(doubleNumbers(numbers));

This is putting out the correct answer in the console, although I have a feeling something is off.

When I change the const numbers=[1, 2, 3] to any other number, I'm still getting 2,4,6. Which leads me to believe function doubleNumbers isn't pulling the numbers from the array, only multiplying the numbers I have in return numbers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Array#map.

const numbers = [1, 2, 3];

function doubleNumbers(numbers) {
    return numbers.map(x => x * 2);
}

console.log(doubleNumbers(numbers));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...