先猜一下下面的代码的结果:
``
JavaScript 字符串方法
请把下面的段落中的“Microsoft”替换为“Apple”:
试一试
请访问 Microsoft!请访问 Microsoft!请访问 Microsoft!
```执行结果是:
replace只替换第一个检索到的Microsoft,
请访问 Apple!请访问 Microsoft!请访问 Microsoft!
那么可如果要全部替换呢?
var txt = str.replaceAll("Microsoft", "Apple");
call() 和 apply()
var person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName:"Bill",
lastName: "Gates",
}
person1.fullName.call(person2); // 会返回 "Bill Gates"
调用person1的函数fullName, 把person2作为this代进去。
所以结果是 Bill Gates
【JavaScript入門】applyって何だ?callとの違いまで徹底解説
<table border="1" cellspacing="0" cellpading="0">
<thead>
<tr class="head">
<td>男子</td>
</tr>
</thead>
<tbody id="deta1">
</tbody>
</table>
<table border="1" cellspacing="0" cellpading="0">
<thead>
<tr class="head">
<td>女子</td>
</tr>
</thead>
<tbody id="deta2">
</tbody>
</table>
// 関数定義
function fnc() {
var num = 1;
for (var j = 0; j < arguments.length; j++) {
var tr = document.createElement("tr");
var td = document.createElement("td");
td.innerHTML = arguments[j];
tr.appendChild(td);
this.appendChild(tr);
num++;
}
}
// 配列の生成
var args = ['阿部太郎','加藤大輔','佐藤勇気','田中雅弘','長島貴之'];
var args2 = ['伊藤文代','木村由美子','清水絵里','茅原梓','西島和美'];
// 関数を呼び出す
var deta1 = document.getElementById("deta1");
fnc.apply(deta1, args);
var deta2 = document.getElementById("deta2");
fnc.apply(deta2, args2);
知道了吧?
関数名.apply(関数の処理の対象となる要素,関数で使う引数(配列のみ) );
関数名.call(関数の処理の対象となる要素,関数で使う引数,関数で使う引数,関数で使う引数… );