如何在 Array<string | RegExp> in Angular2 中增加值



我在Angular2&amp;REGEXP

Angular 2中使用的此包装https://github.com/text-mask/text-mask/

文档https://github.com/text-mask/text-mask/tree/master/angular2#readme

我的问题我可以使用5-6型电话格式

喜欢

  • (xxx)xxx xxxx

  • (xxx)xxx-xxxx

  • xxx-xxx-xxxx

  • xxx xxx xxxx
  • XXXXXXXXXX
  • xxxxx xxxxx

上面的包装阵列格式

我有这种格式

'(', /[1-9]/, /d/, /d/, ')', ' ', /d/, /d/, /d/, '-', /d/, /d/, /d/, /d/

如何添加数组格式

我可以尝试此代码

代码1:

var phoneFormat:Array<string | RegExp>;
 var format="'(','/[1-9]/','/d/','/d/',')',' ','/d/','/d/','/d/',' ','/d/','/d/','/d/','/d/'";
        var ArrayObj=format.split(',');
       for ( var i = 0; i < ArrayObj.length; i++ ) {
          phoneFormat.push(ArrayObj[i]); 
        }

错误给出:

Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined

代码2

 var format=['(','/[1-9]/','/d/','/d/',')',' ','/d/','/d/','/d/',' ','/d/','/d/','/d/','/d/'];
       phoneFormat=format;

代码2没有错误,但掩盖不起作用

如所注释的,您将获得以下错误:

TypeError:无法读取未定义的属性

因为,您尚未初始化数组。

var phoneFormat:Array<string | RegExp>;只是类型定义。您将必须做var phoneFormat:Array<string | RegExp> = [];


现在

"'(','/[1-9]/','/d/','/d/',')',' ','/d/','/d/','/d/',' ','/d/','/d/','/d/','/d/'"

是格式的字符串。因此,当您将其拆分时,您只会获得像"'('"这样的字符串字符串。

您将必须解析它。以下样品将有所帮助:

var phoneFormat: Array <string | RegExp> = [];
var format = "'(','/[1-9]/','/d/','/d/',')',' ','/d/','/d/','/d/',' ','/d/','/d/','/d/','/d/'";
format.split(',').forEach(function(value){
  if(value.startsWith(''/')) {
    phoneFormat.push(new RegExp(value.substring(2, value.length-2)));
  }
  else {
    phoneFormat.push(value.substring(1, value.length-1));
  }
});
console.log(phoneFormat)

最新更新