如何使用 JavaScript 将数组中与特定字符串匹配的元素的名称置空?

如何使用 javascript 将数组中与特定字符串匹配的元素的名称置空?

用 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 = '';    }}

解释:

首先,将 list 中的 name 属性连接成一个字符串,使用 map 和 join。然后,使用 indexof 在连接的字符串中查找 aa 字符串,获取其起始位置 start。如果 start 为 -1,则说明 aa 没有在 list 中找到。接下来,计算 end,它是 start 加上 aa 长度,或 list 的长度(取较小值)。最后,使用一个循环遍历范围 [start, end) 内的元素,并将它们的 name 属性置空。

以上就是如何使用 JavaScript 将数组中与特定字符串匹配的元素的名称置空?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1497648.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Nginx 跨域配置后返回内容错误,是怎么回事?
上一篇 2025年12月19日 19:42:54
data?.map:安全高效地处理数组,合理吗?
下一篇 2025年12月19日 19:43:04

相关推荐

发表回复

登录后才能评论
关注微信