user7423708
user7423708

Reputation:

how to multiply values in an array of numbers in javascript?

var timeCost =[];
var ride_time = 30;
var cost_per_minute = [0.2, 0.35, 0.4, 0.45];

for (let i = 0; i < cost_per_minute.length; i++ ){
  timeCost.push(cost_per_minute[i]*ride_time) 
}

console.log(timeCost)

Upvotes: 0

Views: 2047

Answers (3)

Piyush
Piyush

Reputation: 1162

var ride_time = 30;
var cost_per_minute = [0.2, 0.35, 0.4, 0.45]
var timeCost = cost_per_minute.map(function(i){return i* ride_time})
console.log(timeCost)

Upvotes: 1

zer00ne
zer00ne

Reputation: 43860

Two places in your code:

The 2nd part of a for loop is commonly a condition of the counter (i.e. i) being less than the total count of the array (.ie. cost_per_minute.length)

for (var i = 0; i < cost_per_minute.length; i++ ){

The syntax for an element within an array is nameOfArray[i] with i as the variable index number.

timeCost.push(cost_per_minute[i]*ride_time)

}

var timeCost =[];

var  ride_time = 30;

var cost_per_minute = [0.2, 0.35, 0.4, 0.45];

for (let i = 0; i < cost_per_minute.length; i++ ){

  timeCost.push(cost_per_minute[i]*ride_time) 

}


console.log(timeCost)

Upvotes: 0

Freewalker
Freewalker

Reputation: 7315

This is far more concise with .map():

let cost_per_minute...
const ride_time = 30;
let timeCost = cost_per_minute.map(x => x * ride_time);

Upvotes: 3

Related Questions