有人可以帮助我使用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");
}
但它不能替换这些物品吗?
答案 0 :(得分:0)
使用字符串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>