javascript - 如何在 javascript 数组中找到对象值?
问题描述
我想要做的是在添加之前检查“内容”是否在我的“篮子”中。
我试过这个,但我不明白为什么它不起作用:
function findById(source, tag, content) {
for (var i = 0; i < source.length; i++) {
if (source[i].tag === content) {
return source[i];
}
}
throw "Couldn't find content ";
}
这是我使用它的方式:
var basket = {};
var tag = 'someTag';
var content = 'Joe';
const key = randomFunctions.generateRandomString(); // eg ekkciiuekks
// find out if the content is already in the basket...
var result = findById(basket, tag, content);
if(!result){
// nope... so add it.
basket[key] = {[tag]:content};
}
附言。我想用纯javascript保留答案
更新
当我将鼠标悬停在长度上时,我正在调试并且得到“未定义”:
source.length
回答
对https://stackoverflow.com/users/7668258/maciej-kocik答案稍作修改,即可:
function findById(source, tag, content) {
for (let key in source) {
let property = source[key];
if(property[tag] === content) {
return property[tag];
}
}
return null; // moved this OUTSIDE of for loop
}
解决方案
在你的情况下source.length
是未定义的。您正在添加一个新的对象属性,而不是一个新的数组项。
尝试类似:
function findById(source, tag, content) {
for (let key in source) {
let property = source[key];
if(property[tag] === content) {
return property[tag];
}
throw "Couldn't find content";
}
}
推荐阅读
- android - 使用mobile-ffmpeg android创建视频时出现叠加和缩放问题?
- javascript - 如何在反应中创建复杂的 json(嵌套子到父)?
- java - 在 Eclipse 中,提交选项不可见
- spring-boot - 我无法通过 sql auth 代理在 GCP 中通过 springboot 应用程序从 cloudrun 连接到 cloud sql。有人有一步一步的例子吗?
- jenkins - removeAction/removeViewAction 与 removedJobAction/removedViewAction
- python - 在 python 的 ThreadPoolExecutor 中添加计划
- excel - 从十进制幂查询中拆分非数字
- flutter - 带模态的扩展瓷砖
- python - Scipy 突然为每个包提供错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xdd in position 0: invalid continuation byte
- powerbi - Power BI 从多个文本列中获取最小值