javascript报错“Uncaught TypeError: xxx.replace is not a function”的原因及解决方法。
在字符串以外的对象上使用“replace”时发生。
错误内容
出现在以下对数值执行“replace”的代码中。
const num = 123456; const result = num.replace( /\d/g, '*' ); // ← 发生错误 console.log( result );
错误信息
Uncaught TypeError: num.replace is not a function
错误原因
由于“replace”不能用于数值,所以如果数组中有数值也会出现错误,如下所示。
const arr = ['A11', 111, '222']; const result = arr.map(function (v) { return v.replace( /\d/g, '*' );; }); // Uncaught TypeError: v.replace is not a function console.log( result );
解决方案
用“toString()”转换成字符串后执行。
const num = 123456; const result = num.toString().replace( /\d/g, '*' ); console.log( result ); // ******
或者,判断是否为字符串后再使用。
const num = 123456; const result = typeof num === 'string' ? num.replace(/\d/g) : '不是字符串'; console.log( result ); // 不是字符串