本文介绍了循环访问对象文字并替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能帮我讲解如何使用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方法替换文本&&;更新对象的值

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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>

这篇关于循环访问对象文字并替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 05:02