转换带有多个数字的字符串,然后将所有数字相加

Convert strings with many numbers then add all

本文关键字:数字 然后 转换 字符串      更新时间:2023-09-26

到目前为止,这段代码对我来说是有效的:

 var x;
 var y;
 var z;
function functionWithArgs(x, y, z) {
  console.log(x + y + parseInt(z)); // I get a sum of 6
}
functionWithArgs(1, 2, "3b");

但是当我这样做的时候:

  var x;
  var y;
  var z;
function functionWithArgs(x, y, z) {
  console.log(x + y + parseInt(z)); //
}
functionWithArgs(1, 2, "987b8h76");

我得到一个错误消息。有什么建议吗?我只是个初学者。

试试这个:

function functionWithArgs(x, y, z) {
  console.log(x + y + parseInt(z.replace(/'D+/g, ''), 10));
}
functionWithArgs(1, 2, "987b8h76");  // 987879

试试这个

function functionWithArgs(x, y, z) {
  console.log(x + y + parseInt(z.replace(/'D/g,''))); //
}
functionWithArgs(1, 2, "987b8h76");

我想你需要这个:

var x;
var y;
var z;
function getNum (s) { return s.replace(/[^0-9]/ig,""); }
function functionWithArgs(x, y, z) {
  console.log(x + y + parseInt(getNum(z))); //
}
functionWithArgs(1, 2, "987b8h76");

Javascript parseInt(" som3symbols ")会在解释脚本时导致错误,因为Javascript喜欢单引号。

更改this:

functionWithArgs(1, 2, "987b8h76")

:

functionWithArgs(1, 2, '987b8h76')

如果你在你的代码中运行这个,它将返回990

对于javascript,你可能想要添加:http://www.w3schools.com/jsref/jsref_parseint.asp到你的书签JS, HTML, DOM的超级网站

相关文章: