1

私は、一度終了すると基本的な代数方程式を計算する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

私が試した次のコード:

// 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
4

3 に答える 3

4

文字列は不変です。特定の文字列の内容は変更できません。置換を使用して新しい文字列を作成する必要があります。この新しい文字列を古い変数に割り当てて、変更のように見せることができます。

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 を掛ける方が簡単です。

于 2013-04-12T07:30:55.363 に答える
1

実際の文字列を新しいものに置き換える必要があります

$problem[0][j] = $problem[0][j].replace("+","-");
于 2013-04-12T07:31:55.063 に答える
1

.replace()文字列に変更を加えるのではなく、それらの変更が行われた新しい文字列を返すだけです。

//これは何もしません

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

//これにより、置換された文字列が保存されます

problem[0][j] = problem[0][j].replace("+","-");
于 2013-04-12T07:33:40.230 に答える