如何用JavaScript的for of和for in语句从对象数组中获取指定值
如何修改getValue函数实现指定内容输出?
嘿,我来帮你搞定这个问题!你现在的函数只是把所有值挨个输出,要改成你想要的固定句式,其实只需要在遍历的时候把对应属性的值提取出来再拼接就行,而且完全符合你要求的用for of和for in语句:
首先是完整的修改后的代码:
const customerData = [ { customerName: "Jay", Purchased: "phone", Price: "€200" }, { customerName: "Leo", Purchased: "car", Price: "€2000" }, { customerName: "Luk", Purchased: "Xbox", Price: "€400" }, ]; function getValue(){ // 用for of遍历数组中的每一个客户对象 for(let customer of customerData){ // 先声明变量存储我们需要的三个信息 let customerName = '', purchasedItem = '', itemPrice = ''; // 用for in遍历当前客户对象的所有属性 for(let key in customer){ // 根据属性名,把对应的值存入变量 if(key === 'customerName'){ customerName = customer[key]; } else if(key === 'Purchased'){ purchasedItem = customer[key]; } else if(key === 'Price'){ itemPrice = customer[key]; } } // 按照要求的格式拼接字符串并输出 console.log(`Dear ${customerName} thank you for purchase of a ${purchasedItem} for the price of ${itemPrice}`); } } getValue();
简单解释一下逻辑:
- 外层的
for of循环负责遍历customerData数组里的每一个客户对象,每次循环拿到一个完整的客户信息对象。 - 内层的
for in循环负责遍历当前客户对象的所有属性(也就是customerName、Purchased、Price这些键),通过判断键名来把对应的值提取到预先声明的变量里。 - 最后用模板字符串把三个变量拼接成你想要的句子,用
console.log输出即可。
这样运行之后,控制台就会输出你想要的三条格式化语句啦~
内容的提问来源于stack exchange,提问作者FD3
相关产品推荐
相关产品推荐

