假设x = 120,你有一个数组:[1,2,3,4,5]。
我想创建一个数组,其结果为120除以数组中的每个数字,因此产生
[120,60,40,30,24]?
答案 0 :(得分:2)
您可以使用Array.prototype.map
使用ES5:
var dividedBy120 = [1,2,3,4,5].map(function(currentValue, index, array){
return 120/currentValue;
});
// dividedBy120 = [120, 60, 40, 30, 24]
使用ES6箭头功能:
var dividedBy120 = [1,2,3,4,5].map(currentValue => 120/currentValue);
// dividedBy120 = [120, 60, 40, 30, 24]
答案 1 :(得分:1)
你可以这样做:
var array = [1, 2, 3, 4, 5];
var division_results = []; // The results are stored here.
for (var i = 0; i < array.length; i++){
var result = 120 / array[i]; // This is the result of the division.
division_results.push(result);
}
答案 2 :(得分:0)
使用Array.prototype。map
var dividend = 120;
var divisors = [1,2,3,4,5];
ES5
var quotients = divisors.map(function(divisor){
return dividend / divisor;
);
ES6
var quotients = divisors.map(divisor=> dividend / divisor);