简体   繁体   English

将字符串转换为数组的方法

[英]Method for transform a String into a Array

Does anyone know how to go about converting a string in the following format: 有谁知道如何转换以下格式的字符串:

"I (get (it)) not"

can be converted to be represented as an array? 可以转换为以数组表示? For example, like this: 例如,像这样:

['I', ['get' , ['it']], 'not']

Basically, I want to use parentheses as "levels" in the array. 基本上,我想使用括号作为数组中的“级别”。 I myself know me already a lot of JavaScript but I do not get how I should go about this. 我本人已经知道我很多JavaScript,但是我不知道该怎么做。 I've been trying for 3 hours, but I'm still stuck. 我已经尝试了3个小时,但仍然遇到问题。

Because I'm feeling generous, here's a quick example I made up: 因为我感觉很慷慨,所以这里是一个简单的例子:

// takes a string and returns a array that represents the grouping symbols in the string
function parseString(str)
{  // remove leading and trailing whitespace -- whitespace not important
   str = str.trim();
   // split the string into an array of each of the individual characters
   var arr = str.split('');

   // an array to store the matched parts of the string
   var parsed = [];

   // the current level of the parentheses nesting
   var parentheses = 0;

   // represents the array for each of the parentheses levels
   var levels = [parsed];

   // a shortcut to the array for the current parentheses level
   var current = parsed;

   // parse out any operator that aren't meant to be in the checks
   var notOperators = /^[ ()]*(.*?)[ ()]*$/;

   // count the number of occurrances of a substring in the string
   function count(arg, substring) { return arg.split(substring).length; };

   // check there are the same number of parentheses
   if (count(str, '(') !== count(str, ')')) throw new SyntaxError('Unmatched parentheses');

   // adds the word before the operator/space, if any
   function addPart()
   {  // removes parts already parsed, gets the word
      var beginning = arr.splice(0, i).join('').trim();
      // strips off any operator tokens
      var str = beginning.match(notOperators)[1];
      if (str) current.push(str);
      // since we've removed the parts that we've parsed,
      // we need to reset the loop counter
      i = 0;
   }

   // loop through each of the characters
   for (var i = 0; i < arr.length; ++i)
   {  var token = arr[i];
      // separates words
      if (token === ' ') addPart();
       // opens a new grouping symbol
      else if (token === '(')
      {  addPart();
         // add a new level of hierarchy and keep reference to it
         current.push([]);
         current = levels[++parentheses] = current[current.length - 1];
      }
       // closes an open grouping symbol
      else if (token === ')')
      {  addPart();
         // move one level up the hierarchy of parentheses
         current = levels[--parentheses];
      }

      // make sure something like "a)(" is invalid
      if (parentheses < 0) throw new SyntaxError('Unexpected token )');
   }

   // add the final word before the end of string, if any
   addPart();

   // return the array that represents the string
   return parsed;
}

As you asked, something like: 如您所问,类似:

parseString('The (quick) brown (fox (jumps)) (over the) lazy (dog)');

returns 回报

["The", ["quick"], "brown", ["fox", ["jumps"]], ["over", "the"], "lazy", ["dog"]]

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

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