如何在不保存到其他变量的情况下更改JavaScript中的值

How to change value in JavaScript without saving into another variable

本文关键字:情况下 JavaScript 变量 保存 其他      更新时间:2023-09-26

下面是我的代码,其中我对对象的一些字符串进行了大写,现在当我在下面控制台时,它看起来像是只在for循环中应用的方法的范围(在本例中为toUpperCase)。我知道我可以通过将结果存储/推送到另一个数组/对象中来实现结果,但我想知道JS中是否有任何可用的方法/技术,该方法可以直接应用于原始变量并直接更改其值?

代码-

var odr = {
    testkey1: "a test",
    testkey2: {
        "name": "harris",
        "city": "New York",
        "addr": "107 Suite"
    },
    testkey3: "b test",
};
if(odr.testkey2 !== undefined) {
    for(var key in odr.testkey2) {
        if(odr.testkey2.hasOwnProperty(key)){
            if(typeof odr.testkey2[key] == 'string') {
                console.log(odr.testkey2[key].toUpperCase());
            }    
        }
    }
}
console.log(odr.testkey2);

结果-

Object {name: "harris", city: "New York", addr: "107 Suite"}

工作Fiddle-http://jsfiddle.net/o6d45en6/

我可能误解了你的要求。但是String.toUpperCase()不是bang方法,它只是通过调用该方法来更新其值。因此,如果你想更新值,你需要替换。

if(odr.testkey2 !== undefined) {
    for(var key in odr.testkey2) {
        if(odr.testkey2.hasOwnProperty(key)){
            if(typeof odr.testkey2[key] == 'string') {
                odr.testkey2[key] = odr.testkey2[key].toUpperCase();
            }    
        }
    }
}

仅供参考,在javascript中,当你替换对象时,对象总是传递它的引用。这意味着你不能做这个

var copiedObject = odr;
if(copiedObject.testkey2 !== undefined) {
    for(var key in copiedObject.testkey2) {
        if(copiedObject.testkey2.hasOwnProperty(key)){
            if(typeof copiedObject.testkey2[key] == 'string') {
                copiedObject.testkey2[key] = copiedObject.testkey2[key].toUpperCase();
            }    
        }
    }
}
console.log(odr); // -> odr object has also changed. because copiedObject is just a reference of odr.

为了避免这种情况,您需要deep copy对象。

var copiedObject = JSON.parse(JSON.stringify(odr));

var copiedObject = jQuery.extend({}, odr);
相关文章: