【发布时间】:2019-04-16 03:46:50
【问题描述】:
我想知道 JavaScript 是如何处理代码的,浏览器中发生了什么
代码1(工作代码)
let array = ['Item 1', 'Item 2', 'Item 3'];
array.forEach(function(item) {
if (item === 'Item 2') {
item = item.toUpperCase();
} else {
item = item.toLowerCase();
}
console.log(item);
});
// output item 1
// ITEM 2
// item 3
代码 2(不工作)
let array = ['Item 1', 'Item 2', 'Item 3'];
array.forEach(function(item) {
if (item === 'Item 2') {
item.toUpperCase();
} else {
item.toLowerCase();
}
console.log(item);
});
// output Item 1
// Item 2
// Item 3
【问题讨论】:
-
字符串是不可变的。
-
Item.lowercase 没有第二次保存到项目中。
-
第二个代码未分配项目。它必须像 item = item.toUpperCase();
-
@NinaScholz 这只是其中的一部分。关键是
toUpperCase不会就地修改字符串,但即使字符串是可变的也是如此。
标签: javascript