我有以下代码:
var completename = file.name;
var regex = '/-\w+_/';
var filenameTest_components = completename.match(/-\w+_/);
console.log(completename);
console.log(typeof filenameTest_components, filenameTest_components)
我打算使用数组 filenameTest_components 的前两个元素,但是,当我尝试打印数组的第一个元素时,它给了我错误:
console.log(filenameTest_components[1])
TypeError: Cannot read property '1' of null
有了这个错误,我很困惑匹配方法是否应该返回数组
还是对象
?
如果我仅打印输入字符串并匹配输出,则当前输出如下所示:
task-routelearning_events.json
object [ '-routelearning_',
index: 4,
input: 'task-routelearning_events.json' ]
编辑:
为了提供更大的图片,下面是 github 的链接
最佳答案
当存在匹配时,
String.prototype.match()
始终返回一个数组(否则 null
),但正如您所知,数组是 JavaScript 中的对象。如果在数组上使用 typeof
,您将得到 object
(typeof null
也返回 object
)。因此,确定是否有数组的最佳方法是使用 Array.isArray()。
var str = 'foo bar baz foo',
res = str.match(/foo/g);
console.log(res); // ["foo", "foo"]
console.log(typeof res); // object
console.log(Array.isArray(res)); // true
关于javascript:匹配方法返回对象而不是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44058848/