-5

次のJavaScriptコードの行を説明してください

(function (d, c) {
    d[c] = d[c].replace(/\bno-js\b/, "js");
})(document.documentElement, "className");

この行は、ドキュメント要素のクラス名class="no-js"を次のように置き換えますclass="js"

正常に動作していますが、完全には理解できません。 d[c] = d[c].replace???

4

3 に答える 3

3

なぜこれが反対票を投じられたのかわかりません-可変性についての良い質問のように見えます.

その理由は、文字列は可変ではないためです。文字列を新しい値に置き換えることはできますが、変更することはできません。

正味の結果は、

d[c].replace()

実際に値を変更するのではなく、更新された値で新しい文字列を返します。

戻り値の割り当てを行うことによってのみ、ソースを変更できます。

d[c] = d[c].replace(...)

「置換を行い、置換後の値を元の値として使用する」

于 2013-02-20T21:05:33.840 に答える
1

Firs は関数を作成します

function(d, c){
    d[c] = d[c].replace(/\bno-js\b/,"js");
}

関数を でラップして()、ステートメントではなく式に変換するため、この方法は呼び出し可能であり、引数を渡します

(documentElement, "className")

つまり、次のコードを実行します。

document.documentElement["className"] = document.documentElement["className"].replace(/\bno-js\b/,"js");

次に、ドキュメントのdocumentElementプロパティを取得し、その「className」を正規表現に従って置き換えます。

于 2013-02-20T21:03:15.350 に答える
1
(function(d, c) {
    d[c] = d[c].replace(/\bno-js\b/,"js"); }
)(document.documentElement, "className");

関数は 2 つの引数で呼び出されています。わかりやすくするために、関数内の変数を、関数の呼び出しに使用されている引数に置き換えます。

// Find the element in the DOM identified by "documentElement"
// and access its "className" property, which controls the attribute in
// the markup called "class"
document.documentElement["className"] = 
// Then, take that same property (which is a string), and run
// .replace() on it, with a regex that says "find no-js separated by word
// boundaries", and replace that with js
// Finally, assign the result of that replacement to the original property.
document.documentElement["className"].replace(/\bno-js\b/,"js");
于 2013-02-20T21:04:34.857 に答える