Javascript js-如何在一行中写入match()的访问返回值
这个问题也适用于返回数组作为值的其他函数。我想我看到了一个简短的代码:Javascript js-如何在一行中写入match()的访问返回值,javascript,Javascript,这个问题也适用于返回数组作为值的其他函数。我想我看到了一个简短的代码: var result = "12[abc]34".match(/(\[.*?\])/); alert(result[0]); 那么,有没有一种方法可以将这两行合并为一行,并消除声明结果的必要性呢?试试看 ("12[abc]34".match(/(\[.*?\])/))[0] 试试这个 var result = ("12[abc]34".match(/(\[.*?\])/) || [])[0]; 如果match返回nul
var result = "12[abc]34".match(/(\[.*?\])/);
alert(result[0]);
那么,有没有一种方法可以将这两行合并为一行,并消除声明结果的必要性呢?试试看
("12[abc]34".match(/(\[.*?\])/))[0]
试试这个
var result = ("12[abc]34".match(/(\[.*?\])/) || [])[0];
如果match
返回null
则使用空数组[]
(因为如果在null
中调用[]
,则会出现错误)
如果需要字符串结果,我们还可以使用附加条件
var result = ("12[abc]34".match(/(\[.*?\])/) || [])[0] || '';
var result1=([12[abc]34.match(/(\[.*.\])/)| |[])[0];
console.log(result1);
变量结果=([12[abc]34.match(/(\[.*.\])/)||[])[0]||';
console.log(result)
我们只需将[0]
与match()
方法result直接一起使用即可,如下所示:
alert("12[abc]34".match(/(\[.*?\])/) ? "12[abc]34".match(/(\[.*?\])/)[0] : "No match found");
给出-->[abc]
如果没有找到匹配项,这将处理该情况:
alert("1234".match(/(\[.*?\])/) ? "12[abc]34".match(/(\[.*?\])/)[0] : "No match found");
给出-->未找到匹配项
.是否返回(…)[0]无效?@reporter如果匹配返回空值?