简体   繁体   English

如何求和数组索引值?

[英]How can I sum array index values?

I am new to Javascript and at the moment I'm learning how "arrays" are used.我是 Javascript 的新手,目前我正在学习如何使用“数组”。

In my code below I have 12 numbers held by an array variable.在我下面的代码中,我有 12 个数字由一个数组变量保存。 Next, the for loop is iterating over the indexes to check which values have 2 or more digits, the while-loop then summarizes the digits (eg value '130' at index 8, will be 1+3+0=4).接下来,for 循环遍历索引以检查哪些值具有 2 位或更多位,while 循环然后汇总数字(例如,索引 8 处的值“130”将是 1+3+0=4)。

Final step..and also where I'm stuck:最后一步..还有我被困的地方:

I need to sum up all the "new" index values and return the result in a variable.我需要汇总所有“新”索引值并将结果返回到一个变量中。 With the numbers provided in the code, the result would be '50'.使用代码中提供的数字,结果将是“50”。

Anyone have clue on how to do this?任何人都知道如何做到这一点? I've tried the conventional for-loop with sum += array[i], but it doesn't work.我已经尝试过使用 sum += array[i] 的传统 for 循环,但它不起作用。

 var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1]; for (var i = 0; i < arrChars.length; i++) { var digsum = 0; while (arrChars[i] > 0) { digsum += arrChars[i] % 10; arrChars[i] = Math.floor(arrChars[i] / 10); } var sum = 0; // this last part won't work and I just get "nan", 12 times for (var j = 0; j < arrChars.length; j++) { sum += parseInt(digsum[j]); } console.log(sum); // desired output should be '50' }

Move digsum outside and it will contain the sum of every number in it:digsum外面,它将包含其中每个数字的总和:

 var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1]; var digsum = 0; for (var i = 0; i < arrChars.length; i++) { while (arrChars[i] > 0) { digsum += arrChars[i] % 10; arrChars[i] = Math.floor(arrChars[i] / 10); } } console.log(digsum); // desired output should be '50'

I'd make this easy and just flatten the array of numbers into a string of digits, split that into an array of single digits, and add them together:我会让这变得简单,只需将数字数组展平为一串数字,将其拆分为单个数字数组,然后将它们加在一起:

 var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1]; console.log([...arrChars.join('')].reduce((agg, cur) => agg += +cur, 0));

digsum is a number but you're trying to access it as an array ( digsum[j] ). digsum是一个数字,但您尝试将其作为数组( digsum[j] )访问。 You probably want to overwrite the array with digsum 's value for each index, eg after the while block: arrChars[i] = digsum;您可能想用每个索引的digsum值覆盖数组,例如在while块之后: arrChars[i] = digsum;

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

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