Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript js-如何在一行中写入match()的访问返回值_Javascript - Fatal编程技术网

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如果匹配返回空值?