用 js 将数组中特定名称值置空
问题:
给定一个数组 list,数组中每个元素都是一个对象,具有 name 属性。如何编写一个通用的方法,在 aa 字符串中找到与 list 中各 name 值匹配的项时,将名称置空?
示例:
立即学习“Java免费学习笔记(深入)”;
给定:
var list = [ { "name": "花", "index": 10, "len": 4, "left": 150, "bottom": 108 }, { "name": "花", "index": 0, "len": 4, "left": 150, "bottom": 0 }, { "name": "花", "index": 8, "len": 4, "left": 950, "bottom": 0 }, { "name": "草", "index": 14, "len": 4, "left": 550, "bottom": 108 }, { "name": "草", "index": 15, "len": 4, "left": 650, "bottom": 108 }, { "name": "草", "index": 15, "len": 4, "left": 650, "bottom": 108 } ]; aa = '花花草草';
预期结果:
list = [ { "name": "花", "index": 10, "len": 4, "left": 150, "bottom": 108 }, { "name": "", "index": 0, "len": 4, "left": 150, "bottom": 0 }, { "name": "", "index": 8, "len": 4, "left": 950, "bottom": 0 }, { "name": "", "index": 14, "len": 4, "left": 550, "bottom": 108 }, { "name": "", "index": 15, "len": 4, "left": 650, "bottom": 108 }, { "name": "草", "index": 15, "len": 4, "left": 650, "bottom": 108 } ];
解决方案:
let start = list.map(i => i.name).join('').indexOf(aa); if (start > -1) { let end = Math.min(start + aa.length, list.length); for (let index = start; index < end; index++) { list[index].name = ''; } }
解释:
以上就是如何使用 JavaScript 将数组中与特定字符串匹配的元素的名称置空?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号