如何在javascript中乘以数字数组中的值?

时间:2017-06-23 17:08:05

标签: javascript arrays math

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)

3 个答案:

答案 0 :(得分:3)

这与.map()

更为简洁
let cost_per_minute...
const ride_time = 30;
let timeCost = cost_per_minute.map(x => x * ride_time);

答案 1 :(得分:1)

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)

答案 2 :(得分:0)

代码中的两个位置:

for循环的第二部分通常是计数器的条件(即i)小于数组的总数(.ie。cost_per_minute.length

  

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

数组中元素的语法为nameOfArray[i]i为变量索引号。

  

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)