帮助编写函数 [英] Help Writing a Function
问题描述
编写一个名为crazySum的函数,它接受一个数字数组,并返回每个数字的总和乘以其在数组中的位置。
例如,如果你通过[4,8,15,16],程序将计算4 * 1 + 8 * 2 + 15 * 3 + 16 * 4然后给你回答作为答案。
我是尝试通过采用x(值)和i(放置)然后使用* +来查找总和,但不能提取超过这个值。
这是开始我的解决方案:
Write a function called crazySum that takes an array of numbers, and returns the sum of each number multiplied by its position in the array.
For example, if you pass [4, 8, 15, 16], the program will calculate 4*1 + 8*2 + 15*3 + 16*4 and give you that back as an answer.
I am attempting to work through this by taking an x (value) and i (placement) and then using *+ to find the sum, but can't extract more than just the value.
Here is the beginning of my solution:
var array = [3,2,2];
crazySum = function () {
i=1
for(var i = 1; i<array.length; i++) {
return i
}
}
console.log(crazySum[i]+1);
任何帮助或类似查询的链接都非常感谢=)
Any help or links to similar queries is very much appreciated =)
推荐答案
无论你做什么,函数只返回值1.我建议去JavaScript教程 [ ^ ]并完成教程。
Doesn't matter what you do the function will only ever return a value of 1. I would suggest going to JavaScript Tutorial[^] and working through the tutorials.
最后决定将我的评论作为解决方案发布。
请注意,首先,我不熟悉Java,所以请考虑c是我的评论/语法。
a。)我错过了你想要计算/返回的金额
b。)你的for循环似乎错过了第一个元素。
想想这样的事情:
Finally decided to post my comment as a solution.
Please note first, I'm not familar with Java, so take care with my comment/syntax.
a.) I'm missing the sum you like to calculate/return
b.) Your for Loop seems to miss the first element.
Think about somthing like this:
var sum= 0;
for (var i= 0; i< array.length;i++)
{
sum= sum + (i+1) * Array[i];
}
//此时,sum应具有您所感知的值。
您是否看到了差异?
// At this point, sum should have the value you excpect.
Do you see the differences?
这篇关于帮助编写函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!