JS中使用forEach调用对象方法时属性值为undefined的问题求助
问题分析与解决方案
嘿,我来帮你搞定这个问题~你遇到的undefined问题,核心原因是**forEach调用函数时,this的指向不对**。
为什么会出现undefined?
当你直接把showDetail函数传给forEach时,forEach是把它作为普通函数调用的,这时候函数里的this默认指向全局对象(浏览器环境下是window,Node.js里是global)。而window并没有name、price、sold这些属性,所以打印出来就是undefined;最后那个console: [object Object],是因为window.console本身就是控制台对象,所以直接打印出了它的类型。
而且你数组里的后两个对象自己定义了showDetail方法,但原来的写法并没有调用它们——因为你用的是全局的showDetail,不是对象自身的方法。
解决方法
这里有几种不同的思路,你可以根据需求选:
方法1:给showDetail绑定正确的this
在forEach的回调里,用call或者apply把当前遍历到的game对象绑定为showDetail的this:
function showDetail() { console.log(`name: ${this.name} price: ${this.price} sold: ${this.sold} console: ${this.console}`); } const games = [ { name: 'Crash Bandicoot N. Sane Trilogy', price: 1060, sold: 20, console: 'PS4' }, { name: 'Lego Marvel Super Heroes', price: 700, sold: 25, console: 'XBOX', showDetail: function() { console.log(this.name); } }, { name: 'Gta V', price: 1449, sold: 30, console: 'PS4', showDetail: function() { console.log(this.name); } } ]; // 用call绑定每个game作为this games.forEach(game => showDetail.call(game));
方法2:让showDetail直接接收参数(更推荐,避免this的坑)
把showDetail改成接收一个game对象参数的函数,这样就不用依赖this了,逻辑更清晰:
function showDetail(game) { console.log(`name: ${game.name} price: ${game.price} sold: ${game.sold} console: ${game.console}`); } const games = [ { name: 'Crash Bandicoot N. Sane Trilogy', price: 1060, sold: 20, console: 'PS4' }, { name: 'Lego Marvel Super Heroes', price: 700, sold: 25, console: 'XBOX', showDetail: function() { console.log(this.name); } }, { name: 'Gta V', price: 1449, sold: 30, console: 'PS4', showDetail: function() { console.log(this.name); } } ]; // 直接把当前game传给函数 games.forEach(showDetail);
方法3:优先调用对象自身的showDetail方法
如果你想让数组里那些自己定义了showDetail的对象优先调用自身方法,没有的再用全局的,可以这么写:
function showDetail() { console.log(`name: ${this.name} price: ${this.price} sold: ${this.sold} console: ${this.console}`); } const games = [ { name: 'Crash Bandicoot N. Sane Trilogy', price: 1060, sold: 20, console: 'PS4' }, { name: 'Lego Marvel Super Heroes', price: 700, sold: 25, console: 'XBOX', showDetail: function() { console.log(this.name); } }, { name: 'Gta V', price: 1449, sold: 30, console: 'PS4', showDetail: function() { console.log(this.name); } } ]; games.forEach(game => { if (typeof game.showDetail === 'function') { game.showDetail(); // 调用对象自身的方法 } else { showDetail.call(game); // 用全局方法并绑定this } });
这样修改后,就能正确打印每个对象的属性啦~
内容的提问来源于stack exchange,提问作者Hanna
相关产品推荐
相关产品推荐

