将String转换为数组的方法

时间:2013-11-30 20:44:29

标签: javascript arrays string methods

有谁知道如何转换以下格式的字符串:

"I (get (it)) not"

可以转换为数组吗?例如,像这样:

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

基本上,我想用括号作为"等级"在数组中。我自己已经知道了很多JavaScript,但是我不知道应该怎么做。我已经尝试了3个小时,但我还是卡住了。

1 个答案:

答案 0 :(得分:3)

因为我感觉很慷慨,这是我编写的一个简单例子:

// 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;
}

正如你所问的那样:

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

返回

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