javascript无法删除字符串的第一个字母

javascript无法删除字符串的第一个字母,javascript,replace,substring,Javascript,Replace,Substring,我有一个js函数,一旦完成,它将计算基本代数方程。出于某种原因,它不允许我替换数组中字符串的第一个字符。我以前在这个函数中使用过它,但现在不起作用。我已尝试使用.replace以及.substring 以下是我尝试过的代码: // this is what i've been testing it on // $problem[o][j] = +5 var assi = $problem[0][j].charAt(0); // Get the first character, to replac

我有一个js函数,一旦完成,它将计算基本代数方程。出于某种原因,它不允许我替换数组中字符串的第一个字符。我以前在这个函数中使用过它,但现在不起作用。我已尝试使用.replace以及.substring

以下是我尝试过的代码:

// this is what i've been testing it on
// $problem[o][j] = +5
var assi = $problem[0][j].charAt(0); // Get the first character, to replace to opposite sign
switch (assi){
  case "+":
    console.log($problem[0][j]);
    $problem[0][j].replace("+","-");
    console.log($problem[0][j]);
    break;
}
上述到控制台的输出:

> +5
> +5
> +5
> -+5
我尝试的下一个代码:

// Second code i tried with $problem[0][j] remaining the same
switch(assi){
  case "+":
    console.log($problem[0][j]);
    $problem[0][j].substring(1);
    $problem[0][j] = "-" + $problem[0][j];
    console.log($problem[0][j]);
    break;
}
这将输出到控制台:

> +5
> +5
> +5
> -+5

字符串是不可变的-不能更改特定字符串的内容。您需要使用替换项创建一个新字符串。您可以将这个新字符串分配给旧变量,使其看起来像修改

var a = "asd";
var b = a.replace(/^./, "b"); //replace first character with b
console.log(b); //"bsd";
重新分配:

var a = "asd";
a = a.replace(/^./, "b"); //replace first character with b
console.log(a); //"bsd";

如果你想翻转一个数字的符号,用-1相乘可能更容易。

字符串是不可变的-某个字符串的内容无法更改。您需要使用替换项创建一个新字符串。您可以将这个新字符串分配给旧变量,使其看起来像修改

var a = "asd";
var b = a.replace(/^./, "b"); //replace first character with b
console.log(b); //"bsd";
重新分配:

var a = "asd";
a = a.replace(/^./, "b"); //replace first character with b
console.log(a); //"bsd";

如果你想翻转一个数字的符号,用-1相乘可能更容易。

你需要用新的字符串替换实际的字符串

$problem[0][j] = $problem[0][j].replace("+","-");

您需要用新字符串替换实际字符串

$problem[0][j] = $problem[0][j].replace("+","-");
.replace不会对字符串进行更改,它只会返回一个包含这些更改的新字符串

//这没用

problem[0][j].replace("+","-");
//这将保存替换的字符串

problem[0][j] = problem[0][j].replace("+","-");
.replace不会对字符串进行更改,它只会返回一个包含这些更改的新字符串

//这没用

problem[0][j].replace("+","-");
//这将保存替换的字符串

problem[0][j] = problem[0][j].replace("+","-");

还要注意的是a=a.replace。。。创建一个新的字符串对象并将其指定给。所以如果你需要修改a,你可以这样做:a=a.replace…还要注意a=a.replace。。。创建一个新的字符串对象并将其指定给。因此,如果您需要修改a,您可以执行以下操作:a=a.replace…连续12小时编码时出现的简单错误。>>连续12小时编码时的简单错误。>>