简体   繁体   English

在Javascript数组中彼此分隔数字

[英]Dividing numbers between each other in a Javascript array

I have an array of randomly generated numbers. 我有一个随机生成的数字数组。 I want to create a function that divides all those numbers. 我想创建一个将所有这些数字相除的函数。 Basically, assuming that I have 5 numbers in the array [5, 7, 6, 8, 2], I want the output to be equal to 5 / 7 / 6 /8 / 2 基本上,假设我在数组[5、7、6、8、2]中有5个数字,我希望输出等于5/7/6/8/2

array = [5, 7, 6, 8, 2];

var total = 1;    
for(var i = 0; i < array.length; i++) {
total = array[i] / total; 
}

return total;

This is what I did so far, but the output isn't the correct one. 这是我到目前为止所做的,但是输出不是正确的输出。 Any idea where I am doing wrong? 知道我在哪里做错了吗?

You've basically got your math backwards. 您的数学基本上已经倒退了。 With your approach, you want to progressively divide total, rather than progressively dividing by total. 使用您的方法时,您希望逐步划分总数,而不是逐步划分总数。

var total = array[0];
for (var i = 1; i < array.length; i++) 
    total = total / array[i];
return total;

Try this. 尝试这个。 It uses the array's reduce method along with es6 arrow functions which makes it a one liner. 它使用数组的reduce方法以及es6 箭头函数 ,使它成为一个衬里。 You can use babel to convert es6 syntax to es5. 您可以使用babel将es6语法转换为es5。

var arr = [5, 7, 6, 8, 2];

arr.reduce((prev,curr) => prev/curr);

ES5 version: ES5版本:

var arr = [5, 7, 6, 8, 2];

arr.reduce(function(prev, curr) {
  return prev/curr;
});

As you can see in the docs , Array.reduce() will reduce a list of values to one value, looping through the list, applying a callback function and will return a new list. 正如您在docs中看到的那样 ,Array.reduce()会将值列表减少为一个值,在列表中循环,应用回调函数,并返回一个新列表。 In that callback you can access four parameteres: 在该回调中,您可以访问四个参数:

previousValue: If you pass an argument after callback function, previousValue will assume that value, otherwise it'll be the first item in array. previousValue:如果在回调函数后传递参数,则previousValue将采用该值,否则它将是数组中的第一项。

currentValue: The current value in the loop. currentValue:循环中的当前值。

index: Index of the current item on loop. index:循环中当前项目的索引。

array: The list 数组:列表

Well you messed up with the total, you kept dividing each new number with the result. 好吧,您把总数弄乱了,您不断将每个新数字除以结果。 You just have to flip the '/' operators. 您只需要翻转“ /”运算符即可。

array = [5, 7, 6, 8, 2];

var total = array[0];    
for(var i = 1; i < array.length; i++) {
total = total/array[i]; 
}

return total;

Try this ... 尝试这个 ...

array = [5, 7, 6, 8, 2];
var total = array[0];
for(var i = 1; i < array.length; i++) {
    total = array[i] / total; 
}
return total;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM