遍历对象数组-TypeError:无法读取未定义的属性“名称" [英] Looping through array of objects - TypeError: Cannot read property 'name' of undefined

查看:65
本文介绍了遍历对象数组-TypeError:无法读取未定义的属性“名称"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从下面显示的 artists 数组(例如"Taylor Swift,蕾哈娜,贾斯汀·汀布莱克")中创建艺术家姓名的字符串,但 artist_obj 是未定义的,并且出现错误"TypeError:无法读取未定义的属性'名称'".我该如何解决?

I am trying to create a string of the artist's names from the artists array shown below (i.e. "Taylor Swift, Rihanna, Justin Timberlake"), but the artist_obj is undefined and I get the error "TypeError: Cannot read property 'name' of undefined". How do I fix this?

代码

 //Get info for each song
var artists = item["artists"],
artist = "";
var artists_count = 0;

 artists.forEach(function(item) {
      var artist_obj = item["artists_count"];
      if(artists_count !== 0) {
           artist = artist + ", " + artist_obj["name"];
      } else {
           artist += artist_obj["name"];
      }
      artists_count++;
 });

推荐答案

在您的代码中,您正在使用索引作为 item ["artists_count"] 来访问当前对象.因为"artists_count" 是字符串& ;,不会通过可变的价值!您必须使用 item [artists_count] 其中的双引号来传递变量!除此之外,您的代码还可以!

In your code you are accessing current object using index as item["artists_count"]. This wont work beacuase "artists_count" is a string & wont pass the varible value! You have to use item[artists_count] whichout double quotes to pass the variable! Apart from this you code is okay!

请注意,您传递给 forEach 的参数(即 item )是对当前对象的引用,因此无需保留单独的变量以维护&手动迭代索引.

And please note that the argument, (i.e. item) you are passing to the forEach is the reference to the current object, thus there is no need to keep a separate variable to maintain & manually iterate the index.

将您的代码更改为:

var artists = item["artists"],
artist = "";
var artists_count = 0; 

artists.forEach(function(item) {
      var artist_obj = item;
      if(artists_count !== 0) {
           artist = artist + ", " + artist_obj["name"];
      } else {
           artist += artist_obj["name"];
      }
      artists_count++;
 });

更干净的版本是:

var artists = item["artists"],
artist = "";
artists.forEach(function(item) {
     artist = artist + item["name"] + ", ";
});
artist = artist.replace(/,\s*$/, "");

这篇关于遍历对象数组-TypeError:无法读取未定义的属性“名称"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆