Javascript:用js替换没有js的html类

Javascript:用js替换没有js的html类,javascript,regex,Javascript,Regex,请解释下面一行javascript代码 (function (d, c) { d[c] = d[c].replace(/\bno-js\b/, "js"); })(document.documentElement, "className"); 此行替换文档元素类名 e、 g.类=无js,类=js 它工作得很好,但我不完全理解。 d[c]=d[c]。替换???首先创建函数 function(d, c){ d[c] = d[c].replace(/\bno-js\b/,"js");

请解释下面一行javascript代码

(function (d, c) {
    d[c] = d[c].replace(/\bno-js\b/, "js");
})(document.documentElement, "className");
此行替换文档元素类名 e、 g.类=无js,类=js

它工作得很好,但我不完全理解。
d[c]=d[c]。替换???

首先创建函数

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属性,并根据正则表达式替换其类名

(function(d, c) {
    d[c] = d[c].replace(/\bno-js\b/,"js"); }
)(document.documentElement, "className");
正在使用两个参数调用该函数。为清楚起见,我们将用用于调用函数的参数替换函数中的变量

// 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");

我不知道为什么这会被否决——看起来是一个关于可变性的好问题

原因是字符串是不可变的-可以用新值替换它们,但不能更改它们

最终的结果是

d[c].replace()
实际上不会更改值,而是返回一个带有更新值的新字符串

只有通过对返回值进行赋值,才能使源发生更改

d[c] = d[c].replace(...)
进行替换,然后使用替换后的值作为原始值