javascript - 检查数组是否包含对象时函数未输出正确的值
问题描述
我犯了什么错误?
let array1= [
{no: 1, names: "beef", from: "cow", price: 5},
{no: 2, names: "pork", from: "pig", price: 10},
];
function printByNames(a) {
if (array1.includes(a) == false) {
return (a + " is not a meat!");
} else {
return array1.filter(function (object) {
return console.log(object.names == a);
})[0];
}
}
//test in console = false when should return object.
printByNames("beef")
如果名称在数组中,该函数应该 console.log 整个对象。如果不是,它应该返回输入 + 字符串“不是肉”。
解决方案
你可以像这样得到对象
let array1= [
{no: 1, names: "beef", from: "cow", price: 5},
{no: 2, names: "pork", from: "pig", price: 10},
];
function printByNames(a) {
var arrayobject = array1.find(function (object) {
return object.names == a;
});
return arrayobject ? arrayobject : 'a is not a meat!'
}
printByNames("beef")
推荐阅读
- informatica - Informatica Workflow Manager:如何根据某些条件控制工作流的流程
- servicestack - 冒充用户在 JWT 中嵌入了错误的详细信息
- reactjs - React Table - 使用钩子将访问器值从一个同级表传递到另一个表
- sparql - 我怎样才能有我的三倍数并计算它们呢?(将聚合查询结果添加到非聚合解决方案中)
- java - java流:自定义收集器
- vb.net - 需要合并 2 个文件夹,每个文件夹都有数十万个文件。VB.net
- oauth-2.0 - 获取refreshtoken,Microsoft Graph API 中的accesstoken
- python - 我尝试在我的 Linux Mint 上安装 pyaudio 时出错
- perl - sed 或 Perl 一行 + 如何仅在完全匹配时替换文件中的路径
- laravel - Laravel:订购 hasManyThrough