遍历对象数组进行值比较:修复访问数组对象属性时的‘Cannot read properties of undefined (reading: lowEnd)’错误
解决"Cannot read properties of undefined (reading: lowEnd)"错误并实现餐厅筛选功能
咱们来一步步拆解你遇到的问题,主要有两个核心错误导致了这个报错,同时还有一些代码写法的小细节可以优化:
1. 数组定义的错误写法
你在创建priceArray和restaurants时,用了cheap = {...}这种赋值语句作为数组元素,这不仅会意外创建全局变量,还不是标准的数组元素定义方式。正确的做法是直接在数组中写入对象字面量,不需要额外给元素赋值变量。
2. 函数中错误的属性访问逻辑
你的showRestaurants函数里写了priceArray.price.lowEnd,这里有两个问题:
priceArray是一个数组,它本身并没有price这个属性- 你已经把目标价格区间对象(比如
medium)作为参数传入函数了,直接使用这个参数的lowEnd和highEnd属性就可以,完全不需要再去数组里查找
修正后的完整代码
// 正确定义价格区间数组,直接写入对象字面量 const priceArray = [ {label: "$", lowEnd: 10, highEnd: 20}, {label: "$$", lowEnd: 21, highEnd: 30}, {label: "$$$", lowEnd: 31, highEnd: 40}, ]; // 正确定义餐厅数组 const restaurants = [ {name: "Mcdonalds", averagePrice: 12}, {name: "Sushi", averagePrice: 25}, {name: "Steak", averagePrice: 35} ]; // 用解构赋值获取单个价格区间对象,避免全局变量污染 const [cheap, medium, expensive] = priceArray; function showRestaurants(targetPriceRange) { // 使用filter方法筛选餐厅,代码更简洁易读 const matchedRestaurants = restaurants.filter(restaurant => { return restaurant.averagePrice >= targetPriceRange.lowEnd && restaurant.averagePrice <= targetPriceRange.highEnd; }); console.log(matchedRestaurants); // 也可以返回筛选结果供后续使用 return matchedRestaurants; }; // 调用函数,传入中等价格区间对象 showRestaurants(medium);
代码细节说明
- 数组定义:去掉了多余的变量赋值,改用解构赋值获取单个价格区间对象,避免全局变量污染。
- 筛选逻辑:用
Array.filter()替代for循环,代码更简洁直观,直接使用传入的targetPriceRange参数的属性进行判断,彻底解决了属性访问undefined的问题。 - 边界处理:把判断条件中的
<改成<=,确保刚好等于区间上限的餐厅也能被正确筛选(比如均价30的餐厅会被归到中等价位)。
这样修改后,你的函数就能正常筛选对应价格区间的餐厅,再也不会出现那类属性访问错误啦。
内容的提问来源于stack exchange,提问作者Nick Johnson
相关产品推荐
相关产品推荐

