[英]JavaScript : searching an array and returning value after user input
var data = [{
id: 'A1',
name: 'Minstrels'
}, {
id: 'A2',
name: 'Bounty'
}, {
id: 3,
name: 'Crunchie'
}, {
id: 4,
name: 'bar'
}];
var rl = require('readline')
var prompts = rl.createInterface(process.stdin, process.stdout);
prompts.question('Which Product do you want to purchase? ',
function(Answer1) {
//missing code goes here in order to return Minstrels if the user
//types 'A1' etc..
}
)
我的代碼需要幫助。 我啟用了用戶輸入並創建了一個數組,但是,我無法想到我的代碼丟失了什么。
這使用find()
數組方法來定位與給定謂詞匹配的第一個元素,然后另外處理未定位該項的情況。 因為您的示例同時使用字符串和數字作為id
值,所以在比較期間我們將每個對象的id
顯式強制為字符串,以簡化嚴格的比較:
var item = data.find(i => ("" + i.id) === Answer1);
console.log(item ? item.name : 'No such food');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.