简体   繁体   English

jQuery for(x在y)循环

[英]jQuery for(x in y) loop

In the following code the variable " key " isn't capitalized even though any other variables, such as steve[j], are capitalized if they replace " key " in the call to the function capitaliseFirstLetter() . 在下面的代码中,即使将任何其他变量(例如steve [j])替换为对函数capitaliseFirstLetter()的调用中的“ key ”,变量“ key ”也不大写。

Could someone tell me why? 有人可以告诉我为什么吗?

for(key in aray) {
    steve = aray[key];
    for(j = 0; j < steve.length; j++){
        diff = steve[j].slice(key.length);
        if(diff == ""){
            diff = "_";
        }
        diffs.push(diff);
        var firstLetterUpper = /^[A-Z]/.test(steve[j]);
        if(firstLetterUpper){
            capitaliseFirstLetter(key)
            alert(key])
        }

    }
}
function capitaliseFirstLetter(string){
    return string.charAt(0).toUpperCase() + string.slice(1);
}
key = capitaliseFirstLetter(key)
alert(key)

string object is passed to function by value. 字符串对象按值传递给函数。 So it's not changing you should reaasign value 所以这并没有改变,您应该重新分配价值

If your aim is to captitalise each word it can be done more simply as: 如果您的目标是将每个单词都大写,则可以更简单地完成以下操作:

JSFiddle: http://jsfiddle.net/UgT3x/ JSFiddle: http : //jsfiddle.net/UgT3x/

for (key in aray) {
    var steve = aray[key];
    console.log(toTitleCase(steve));
    // if you want to change the aray value
    aray[key] = toTitleCase(steve);
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM