【问题标题】:Why the first code works and the second does not work? [duplicate]为什么第一个代码有效而第二个代码无效? [复制]
【发布时间】: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


【解决方案1】:

item.toUpperCase(); 返回大写字符串,这就是为什么当你这样做时 item = item.toUpperCase(); 大写的字符串被分配给item,由于item 是一个数组元素,该元素被它的引用改变了。

【讨论】:

    【解决方案2】:

    这里 item = item.toUpperCase(); 粗体是创建一个正在打印的局部变量,但在后一种情况下,它只是引用和正在打印的函数参数

    【讨论】:

    • 在这两种情况下,item 都是局部变量,但第一次保存更改,第二次不保存
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多