簡體   English   中英

修改鍵值對Javascript中的字符串

[英]Amend strings in key-value pairs Javascript

我需要更改數組中字符串的所有實例,我可以這樣做,但是當它們是鍵值對時,沒有更好的解決方案嗎?

var person = [];
person.push({
    name: 'John Smith',
    description: 'John Smith is tall.',
    details: 'John Smith has worked for us for 10 years.'
});
person.push({
    name: 'Michael Smith',
    description: 'Michael Smith is tall.',
    details: 'Michael Smith has worked for us for 10 years.'
});
person.push({
    name: 'Linda Smith',
    description: 'Linda Smith is tall.',
    details: 'Linda Smith has worked for us for 10 years.'
});

function replaceWordST() {
    var toReplace = "Smith";
    var replaceWith = "Jones";
    for (i = 0; i < person.length; i++) {
        person[i].name = person[i].name.replace(new RegExp(toReplace, 'g'), replaceWith);
        person[i].description = person[i].description.replace(new RegExp(toReplace, 'g'), replaceWith);
        // etcetc
    }
}

像對象一樣: http//jsfiddle.net/mig1098/ekLmquap/

var replace = {
        replaceWordST:function(person) {
            var toReplace = /Smith/g;
            var replaceWith = "Jones";
            jsonData = person;
            for(var obj in jsonData){
                    if(jsonData.hasOwnProperty(obj)){
                    for(var prop in jsonData[obj]){
                        if(jsonData[obj].hasOwnProperty(prop)){
                            jsonData[obj][prop] = replace.name(jsonData[obj][prop],toReplace,replaceWith);
                        }
                    }
                }
            }
            return jsonData;
        },
        name:function(name,toReplace,replaceWith){
            return name.replace(toReplace, replaceWith);
        }
}

更優雅的解決方案

您可以使用嵌套循環來減少相似行的數量

function replaceWordST() {
    var toReplace = "Smith",
        replaceWith = "Jones",
        re = new RegExp(toReplace, 'g'), // cache this!!
        keys = ['name', 'description', 'details' /*, etc*/],
        i, j; // don't forget to var these!!
    for (i = 0; i < theURLs.length; ++i) {
        for (j = 0; j < keys.length; ++j) {
            person[i][keys[j]] = person[i][keys[j]].replace(re, replaceWith);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM