简体   繁体   English

如何拆分字符串,转换为数字和总和

[英]How to split String, convert to Numbers and Sum

I have a function that I have modified to get a string (which consists of zeros and ones only). 我有一个已修改为获取字符串(仅包含零和一)的函数。 The string ( timesheetcoldata ): 字符串( timesheetcoldata ):

100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000

The string items (the numbers one and zero) will change every time the function is run. 字符串项(数字一和零)将在每次运行该函数时更改。 It will always be the same length. 长度将始终相同。 I have made the string above easier to see what I am trying to achieve. 我使上面的字符串更容易理解我要实现的目标。

I want to return the first character and then every 24th character (as in the variable colsCount in the function). 我想返回第一个字符,然后每24个字符(如函数中的colsCount变量一样)。 so, in the example above, it would return something like: 111111 因此,在上面的示例中,它将返回类似以下内容的内容: 111111

I then want to convert these characters to numbers (something like [1, 1, 1, 1, 1, 1] ). 然后,我想将这些字符转换为数字(类似[1, 1, 1, 1, 1, 1] )。

I then want to sum these number together (so it would return, in the example: 6 ). 然后,我想将这些数字加起来(因此在示例中将返回6 )。

I then want to check if the returned number matches the variable: rowsCount or true if it does, false if it does not. 然后,我想检查返回的数字是否与变量匹配: rowsCounttrue如果匹配, rowsCount false

My function: 我的功能:

$("#J_timingSubmit").click(function(ev){

  var sheetStates = sheet.getSheetStates();
  var rowsCount = 6;
  var colsCount = 24;
  var timesheetrowsdata = "";
  var timesheetcoldata = "";

  for(var row= 0, rowStates=[]; row<rowsCount; ++row){
    rowStates = sheetStates[row];
    timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
  }

  timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
  console.log(timesheetcoldata);
});

Thank you very much to both Rajesh and MauriceNino (and all other contributers). 非常感谢Rajesh和MauriceNino(以及所有其他贡献者)。

With their code I was able to come up with the following working function: 通过他们的代码,我能够提出以下工作功能:

$("#J_timingSubmit").click(function(ev){

  var sheetStates = sheet.getSheetStates();
  var rowsCount = 6;
  var timesheetrowsdata = "";
  var timesheetcoldata = "";

  for(var row= 0, rowStates=[]; row<rowsCount; ++row){
    rowStates = sheetStates[row];
    timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
  }

  timesheetcoldata = timesheetrowsdata.replace(/,/g, '');

var count = 0;
var list = [];
for(var i = 0; i< timesheetcoldata.length; i+=24) {
  const num1 = Number(timesheetcoldata.charAt(i));
  list.push(num1);
  count += num1;
}

let isSameAsRowsCount = count == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);

});

You can always rely on traditional for for such action. 您始终可以依靠传统for执行此类操作。 Using functional operations can be more readable but will be more time consuming( though not by much ). 使用功能性操作可能更具可读性,但会更加耗时( 尽管不是很多 )。

You can try this simple algo: 您可以尝试以下简单算法:

  1. Create a list that will hold all numbers and a count variable to hold sum. 创建一个将包含所有数字的列表和一个用于保存和的count变量。
  2. Loop over string. 遍历字符串。 As string is fixed, you can set the increment factor to the count( 24 ). 由于字符串是固定的,因此可以将增量因子设置为count( 24 )。
  3. Convert the character at given index and save it in a variable. 转换给定索引处的字符并将其保存在变量中。
  4. Push this variable in list and also compute sum at every interval. 在列表中推送此变量,并在每个时间间隔计算总和。

At the end of this loop, you have both values. 在此循环结束时,您将拥有两个值。

 var string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000'; var count = 0; var list = []; for(var i = 0; i< string.length; i+=24) { const num1 = Number(string.charAt(i)); list.push(num1); count += num1; } console.log(list, count) 

Here is a step by step explanation, on what to do. 这是有关操作的逐步说明。

  • Use match() to get every nth char 使用match()获取第n个字符
  • Use map() to convert your array elements 使用map()转换数组元素
  • Use reduce() to sum your array elements 使用reduce()对数组元素求和

Everything needed to say is included in code comments: 需要说明的所有内容都包含在代码注释中:

 const testData = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000'; // Step 1) Create array of numbers from string const dataArr = testData.match(/.{1,24}/g) // Split on every 24th char .map(s => Number(s[0])) // Only take the first char as a Number console.log(dataArr); // Step 2) Sum array Numbers let dataSum = dataArr.reduce((a, b) => a + b); // Add up all numbers console.log(dataSum); // Step 3) Compare your variables let rowsCount = 123; // Your Test variable let isSameAsRowsCount = dataSum == rowsCount; console.log('Is Same? ', isSameAsRowsCount); 

As @Jaromanda mentioned, you can use the following to done this. 如@Jaromanda所述,您可以使用以下代码来完成此操作。

 const string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000'; const value = string.split('').filter((e,i)=> !(i%24)).reduce((acc,cur)=> acc+ (+cur), 0); console.log(value); 

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

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