Javascript 在以下数组中匹配双引号
这是数组的数组:Javascript 在以下数组中匹配双引号,javascript,arrays,regex,Javascript,Arrays,Regex,这是数组的数组: [ '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] ===
[ 'markdown',
[ 'para', 'This is a ', [ 'em', 'test' ] ],
[ 'hr' ],
[ 'para', {class: 'noind'}, 'another test' ],
[ 'para', '"test with double quotes"' ],
我知道如何匹配para
s:
for (i = 1; i < jsonml.length; i++) {
if (jsonml[i][0] === 'para') {
// do stuff
}
}
但是我得到了
类型错误:无法调用未定义的方法“match”。可能是因为[hr]
或['para',{class'noind'},'另一个测试']
?如果是,如何使代码工作?在对其使用.match()
之前,必须先测试该值是否为字符串
if (jsonml[i][0] === 'para' && typeof jsonml[i][1] === "string" && jsonml[i][1].match(/"/g)) {
您的一些jsonml[i][1]
值不存在或不是字符串,因此它们不会有.match()
方法,然后您会得到该异常。
查找嵌套数组中带双引号的字符串的简单实用方法:
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);
出现此错误是因为某些数组只有1个元素。请检查我的答案中的通用实用程序方法,该方法可以检测嵌套数组@alexchenco中的双引号
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);