有人可以帮助我了解如何使用jQuery $.each遍历对象文字并替换每个项目中匹配的字符串的语法吗?

如果我有:

var foo = {
    item1: "Mary had a little lamb",
    item2: "Whose fleece was white as snow",
    item3: "Johnny ha a little lamb",
    item4: "What's the deal with lambs?"
}


我想将lamb替换为lion,在$ .each函数内的哪个位置替换该项目?

我试过了:

$.each(foo, function(key, value){
     return value.replace(/lamb/, "lion");
}


但是它不能代替物品吗?

最佳答案

使用字符串replace方法替换文本并更新对象的值



var foo = {
  item1: "Mary had a little lamb",
  item2: "Whose fleece was white as snow",
  item3: "Johnny has a little lamb",
  item4: "What's the deal with lambs?"
}
$.each(foo, function(i) {
  foo[i] = foo[i].replace('lamb', 'lion')
});
console.log(foo)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

09-19 03:17