简体   繁体   English

JavaScript:从数组中排序整数和运算符

[英]JavaScript: Sorting integers and operators from array

Here is my jsfiddle: JSFIDDLE 这是我的jsfiddle: JSFIDDLE

So, I'm trying to get an output that shows 3 different objects: 因此,我尝试获取显示3个不同对象的输出:

// Wanting to get 
// {
// 0: {type: "number", value: 22},
// 1: {type: "operator", value: "+"},
// 2: {type: "number", value: 22},
// }

function lexer(contents) {
  const tokens = [];

  while (contents.length) {
    let char     = contents[0];
    contents = contents.slice(1);

    if (/[-+*\/]/.test(char)) {
      tokens.push({ type: 'operator', value: char });
    }

    let number = '';
    while (/[1-9]/.test(char)) {
      number += char;
      char = contents[0];
      contents = contents.slice(1);
    }

    if (number !== '') {
      tokens.push({ type: 'number', value: parseInt(number, 10) });
    }
  }
  return tokens;
}

const result = lexer(["2", "2", "+", "2", "2"]);

Now I'm just going to fill out more text. 现在,我将填写更多文本。 I'm not exactly sure what is wrong with this code as it seems to be skipping one of the outputs. 我不确定这段代码有什么问题,因为它似乎正在跳过其中一个输出。 I'm guessing it has something to do with the while loop. 我猜想它与while循环有关。

Your issue is that you're slicing contents before verifying that it's a number. 您的问题是您在验证contents是数字之前先对contents进行切片。 Thus, when it reaches the + it has already sliced it off of the array before it pushes the token and when the next loop with the condition contents.length comes around, the plus will have been dropped and you have no way to know that it was there. 因此,当它达到+它已经切它关闭阵列的它推动令牌,并在与条件下一循环之前contents.length恶有恶报,正将已被丢弃,你有没有办法知道它在那儿。

I would suggest that instead of slicing right after reading the character, only slice once you've used the character in some way, ie after you've pushing the operator token or appended the char to number . 我建议不要在读取字符后立即进行切片,而仅在以某种方式使用字符后才进行切片,即在按下运算符或将char附加到number

function lexer(contents) {
  const tokens = [];

  while (contents.length) {
    let char     = contents[0];

    if (/[-+*\/]/.test(char)) {
      tokens.push({ type: 'operator', value: char });
      contents = contents.slice(1);
    }

    let number = '';
    while (/[1-9]/.test(char)) {
      number += char;
      contents = contents.slice(1);
      char = contents[0];
    }

    if (number !== '') {
      tokens.push({ type: 'number', value: parseInt(number, 10) });
    }
  }
  return tokens;
}

It's a subtle difference, but this way you aren't changing your array until after you've used the data, thus ensuring consistency. 这是一个细微的差异,但是通过这种方式,您直到使用完数据后才更改数组,从而确保了一致性。

Updated fiddle: https://jsfiddle.net/semhw54y/10/ 更新的小提琴: https : //jsfiddle.net/semhw54y/10/

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

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