简体   繁体   English

JavaScript 中的数组元素之和

[英]Sum of array elements in JavaScript

I'm trying to solve this problem where I initialize an array of 5 elements and print the sum of the elements.我试图解决这个问题,我初始化一个包含 5 个元素的数组并打印元素的总和。 I can't wrap my head around the logic behind the solution.我无法理解解决方案背后的逻辑。 Please review my code.请查看我的代码。

Another problem with reading an array of 5 integers and printing the smallest element.读取 5 个整数的数组并打印最小元素的另一个问题。 I keep getting the wrong answer...我总是得到错误的答案...

This's a script embedded inside an HTML file.这是嵌入在 HTML 文件中的脚本。

Problem 1问题 1

var num= [1,1,1,1]; 

var total=num[0];
for( var i=0 ; i < num.length ; i++)
    { 

     total =+num[i]; 
    }


window.alert("The total is "+ total); 

I expected the answer to be 4, but all I get is 1.我预计答案是 4,但我得到的只是 1。


Problem 2问题 2

var r = new Array(5);

var len = r.length; 

for(var i=0 ; i <len ; i++)
    {
        r[i] = window.prompt("Enter the elements of the array");
    }


 var small= [0];

for(var j=0; j< len ; j++)
    { 
     if(r[i] < small )
         small = r[i];
    }

window.alert("The smallest element is the array is "+small);

I get the last element in my array as the smallest element which's obviously isn't right.我将数组中的最后一个元素作为最小元素,这显然是不正确的。

In problem 1) you just need to change =+ to +=在问题 1) 中,您只需将 =+ 更改为 +=

In problem 2) you need to start in the first element of r and in the for loop you need index the r array by the variable j instead of i variable在问题 2)中,您需要从r的第一个元素开始,在 for 循环中,您需要通过变量j而不是i变量来索引r数组

var r = new Array(5);
var len = r.length; 

for(var i=0 ; i <len ; i++)
{
    r[i] = window.prompt("Enter the elements of the array");
}

var small = r[0];

for( var j=0; j< len ; j++)
{ 
    if(r[j] < small )
        small = r[j];
}

window.alert("The smallest element is the array is "+small);

But you could just do:但你可以这样做:

const min = Math.min(...r)
window.alert("The smallest element is the array is "+ min);

There are a couple things here.这里有几件事。

For problem 1: Since you initialize the total to the first item I think you end up counting it 2 times.对于问题 1:由于您将total初始化为第一项,我认为您最终计算了 2 次。 Likely you'd want to initialize to 0. var total = 0 .您可能希望初始化为 0。 var total = 0 You will also want to use += instead of =+ the latter sets the value instead of adding it.您还需要使用+=而不是=+后者设置值而不是添加它。

For Problem 2: new Array(5) creates a new sparse array.对于问题 2: new Array(5)创建一个新的稀疏数组。 It's kinda weird.这有点奇怪。 It's like it's full of undefined values.就像它充满了undefined的值。 So when you assign small you'll want to access the first element of r , var small = r[0] but that will be undefined due to r being a sparse array.因此,当您分配small时,您将希望访问r的第一个元素, var small = r[0]但由于r是稀疏数组,因此该元素undefined So you'll want var r = new Array(5).fill().map((x,i) => i) to set values in that array.因此,您需要var r = new Array(5).fill().map((x,i) => i)在该数组中设置值。 You will also want to use j instead of i in the body of the second loop.您还需要在第二个循环的主体中使用j而不是i

That should do it;).那应该这样做;)。

Hi The problem 1 could be tackled with reduce method check the Docs here :您好问题 1 可以通过 reduce 方法解决,请查看此处的文档:

The problem 2 could be solved with Math.min method:问题 2 可以用 Math.min 方法解决:

var num= [1,1,1,1]; 
var numMin= [100,1121,1212,122, 12]; 

//Problem1
let totalSum = num.reduce( ( accumulator, currentItem ) => {
 return accumulator = accumulator += currentItem;
} , 0 );

console.log(totalSum)

//Problem 2
console.log( 'Min',Math.min( ...numMin ) );

Here is a replit so you can play with the code这是一个replit ,因此您可以使用代码

 // Find array elements sum let total = 0; let arr = [1,2,3,4]; arr.map(el => total+=el); console.log(total); // 10

 // Find array smallest element let arr = [1,-2,13,-4,7]; let smlEl = arr[0] arr.map(el => { if(el < smlEl) { smlEl = el; } }) console.log(smlEl); // -4

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

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