将Javascript数组对象转换为大写

时间:2016-03-04 01:18:20

标签: javascript arrays

var contacts =[];

function getInfo() {
    var firstName = prompt("Enter first name");
    var lastName = prompt("Enter last name");
    var emailId = prompt("Enter Email ID");
    var phoneNo = prompt("Enter Phone number");
    var fname, lname, email, phone;
    var person ={
        fname : firstName,
        lname : lastName,
        email : emailId,
        phone : phoneNo
    }
    contacts.push(person);  
}

如何将contacts数组转换为大写?将数组转换为大写后,我想按字母顺序显示全名,如图所示。或者有没有其他方法可以完成而不转换为大写?

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用它将字符串转换为标题大小写:

var width = $(window).width(); 
var height=$(window).height(); 
var mydiv=$("#mydiv");
mydiv.width(width);
mydiv.height(height);

$(window).resize(function(){
  width = $(window).width();
  height=$(window).height();
  mydiv.width(width);
  mydiv.height(height);

});

参见示例用法:

function toTitleCase(str) {
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

结果是:

var nameMixedCaseing = ["alan bong" , "JusTin weasel", "Tom curry"]

for (i = 0; i < nameMixedCaseing.length; i++)
    console.log(toTitleCase(nameMixedCaseing[i]));

因此,在您的代码中,您可以在保存人物对象之前调用此函数

Alan Bong
Justin Weasel
Tom Curry

答案 1 :(得分:0)

您可以使用一组函数,一个用于大写,一个用于在每次将新联系人推入阵列时进行排序:

var contacts = [
    { 
        fname: 'andrew',
        lname: 'mCGonahan'
    },
    { 
        fname: 'paUla',
        lname: 'Ptrokva'
    },
    { 
        fname: 'kevin',
        lname: 'harGRove'
    },
    { 
        fname: 'CAmille',
        lname: 'dUpoIs'
    },
    { 
        fname: 'AlbERt',
        lname: 'sWanson'
    }
];

function capitalize(arr) {
    for (var i = 0; i < arr.length; i++) {
        var first = arr[i].fname;
        var last = arr[i].lname;
        arr[i].fname = first.slice(0,1).toUpperCase() + first.slice(1).toLowerCase();
        arr[i].lname = last.slice(0,1).toUpperCase() +last.slice(1).toLowerCase();
    }
    return arr;
}

function sortByLast(arr) { 
    return arr.sort(function(a, b) { 
        if (a.lname > b.lname) return 1;
        if (b.lname > a.lname) return -1;
        return 0;
    });
}

//you can call the following after you have pushed the newest contact into the array
// or you could capitalize the inputs as they are entered, then run the sort function on the contacts array
contacts = sortByLast(capitalize(contacts));


document.getElementById('sortedContacts').innerHTML  = JSON.stringify(contacts);
<div id="sortedContacts"><h3></h3></div>