【问题标题】:Matching double quotes in the following array of arrays匹配以下数组数组中的双引号
【发布时间】:2015-03-02 16:42:15
【问题描述】:

这是数组数组:

[ 'markdown',
  [ 'para', 'This is a ', [ 'em', 'test' ] ],
  [ 'hr' ],
  [ 'para', {class: 'noind'}, 'another test' ],
  [ 'para', '"test with double quotes"' ],

我知道怎么匹配paras:

for (i = 1; i < jsonml.length; i++) {
  if (jsonml[i][0] === 'para') {
    // do stuff
  }
}

现在我只想匹配带有双引号 ([ para, '"test with double quotes"' ]) 的 paras。

我试过了:

if (jsonml[i][0] === 'para' && jsonml[i][1].match(/"/g)) {

但我得到TypeError: Cannot call method 'match' of undefined。也许是因为[hr][ 'para', {class: 'noind'}, 'another test' ]?如果是这样,我怎样才能使代码工作?

【问题讨论】:

  • 您收到此错误是因为您的某些数组只有 1 个元素。
  • 检查我的答案中的通用实用程序方法,它可以检测嵌套数组@alexchenco 中的双引号

标签: javascript arrays regex


【解决方案1】:

JSBIN DEMO

在嵌套数组中查找带双引号的字符串的简单实用方法:

   var array = [ 'ma"r"kdown', [ 'para', 'This is a ', ['em', 'test']],
      [ 'hr' ],
      [ 'para', {class: 'noind'}, 'another test' ],
      [ 'para', '"test with double quotes"' ]];

    function checkDoubleQuotes(array) {
      array.forEach(function(value) {
        if({}.toString.call(value)==="[object Array]") {
           return checkDoubleQuotes(value); 
        }
        if(typeof value==='string' && value.match(/"/g)) {
          console.log("matched : "+value);
        }

      })
    }

    checkDoubleQuotes(array);

【讨论】:

    【解决方案2】:

    在使用 .match() 之前,您必须测试该值是否为字符串。

    if (jsonml[i][0] === 'para' && typeof jsonml[i][1] === "string" && jsonml[i][1].match(/"/g)) {
    

    您的某些 jsonml[i][1] 值不存在或不是字符串,因此它们不会有 .match() 方法,然后您会得到该异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多