简体   繁体   English

无法将值推入对象数组?

[英]Unable to push value onto Object Array?

So I have some code im working through on FreeCodeCamp: https://jsfiddle.net/matt40413/m8wh7sxz/ 所以我在FreeCodeCamp上正在处理一些代码: https ://jsfiddle.net/matt40413/m8wh7sxz/

Everything is working great until I try to push a value onto a new array (that doesn't exist yet) I get the error Uncaught TypeError: collectionCopy[id].tracks.push is not a function . 一切正常,直到我尝试将值推入新数组(尚不存在)之前,我收到错误Uncaught TypeError: collectionCopy[id].tracks.push is not a function

  if(prop == "tracks")
  {
    collectionCopy[id]["tracks"].push(value);
  }

This is where it's failing. 这是失败的地方。 But the funny thing is, if I MANUALLY put everything in such as: collectionCopy[5439]["tracks"].push("Whatever") works just fine! 但是有趣的是,如果我手动将所有内容放进去,例如: collectionCopy[5439]["tracks"].push("Whatever")效果很好!

So what's going on here? 那么这是怎么回事? Im essentially doing the same thing? 我基本上在做同样的事情? but just using the parameters instead (Which btw my other functions do work, so im a bit confused). 但是只使用参数即可(我的其他功能确实起作用,所以我有点困惑)。

Three comments about the code: 关于代码的三个注释:

  1. You are using the if-else statements as separated cases, that is not true! 您将if-else语句用作单独的情况,这是不正确的! In order to separate each case, you should use else if statement 为了区分每种情况,应使用else if语句

  2. The problem in the code is that your first case was 代码中的问题是您的第一种情况是

    if(!collectionCopy[id][[prop]]) 如果(!collectionCopy [ID] [道具])

That is saying: if the key [prop] doesn't exists in collectionCopy[id] , then ... 就是说:如果键[prop]collectionCopy [id]中不存在,则...

Since [prop] is an array and not a number neither a string, the expression was always true. 由于[prop]是一个数组,而不是数字,也不是字符串,因此表达式始终为true。 Therefore, it was executing collectionCopy[id][prop] = value . 因此,它正在执行collectionCopy [id] [prop] = value

Note: the keys are always string or numbers. 注意:键始终是字符串或数字。

  1. The rest of the code was correct and actually cool. 其余代码是正确的,而且实际上很酷。

This is the corrected snippet. 这是已更正的代码段。

// Setup
var collection = {
    "2548": {
      "album": "Slippery When Wet",
      "artist": "Bon Jovi",
      "tracks": [ 
        "Let It Rock", 
        "You Give Love a Bad Name" 
      ]
    },
    "2468": {
      "album": "1999",
      "artist": "Prince",
      "tracks": [ 
        "1999", 
        "Little Red Corvette" 
      ]
    },
    "1245": {
      "artist": "Robert Palmer",
      "tracks": [ ]
    },
    "5439": {
      "album": "ABBA Gold"
    }
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));

// Only change code below this line
function updateRecords(id, prop, value) {

  if(!collectionCopy[id][prop])
  {
  collectionCopy[id][prop] = value;
  }
  else if(value == "")
  {
  console.log("DELETED");
    delete collectionCopy[id][prop.push]
  }
  else if(prop == "tracks")
  {
    collectionCopy[id]["tracks"].push(value);
  }
    console.log(collectionCopy);





  return collection;
}

// Alter values below to test your code
updateRecords(5439, "tracks", "Take a Chance on Me");

Working example https://jsfiddle.net/m8wh7sxz/2/ 工作示例https://jsfiddle.net/m8wh7sxz/2/

Change this part: 更改此部分:

collectionCopy[id]["tracks"].push(value);

To: 至:

collectionCopy[id]["tracks"] = value;

Because collectionCopy[id]["tracks"] is not initialized yet, there for you can't call push() function 由于collectionCopy[id]["tracks"]尚未初始化,因此您无法调用push()函数

You simply initialized your object incorrectly, doing this will fix it: 您只是简单地错误地初始化了对象,这样做可以解决该问题:

updateRecords(5439, "tracks", ["Take a Chance on Me"]);

Now your push will append to this array! 现在,您的推送将追加到此数组! Before you were trying to run .push() on a string! 在尝试对字符串运行.push()之前!

Edit: 编辑:

If you need to dynamically construct the array when updating, you can do: 如果需要在更新时动态构造数组,则可以执行以下操作:

if (prop == "tracks") {
  console.log(collectionCopy[id]["tracks"])
  if (!(collectionCopy[id]["tracks"] instanceof Array)) {
    collectionCopy[id]["tracks"] = [value]
  } else collectionCopy[id]["tracks"].push(value)
}

You don't have "tracks" in "5439" object. 您在“ 5439”对象中没有“轨道”。

You should add it if you want to access it as array. 如果要以数组形式访问它,则应添加它。

"5439": {
  "album": "ABBA Gold",
  "tracks":[]
}

EDIT: 编辑:

This should work for you then. 然后,这应该为您工作。

else if(prop == "tracks")
{
   if(!("tracks" in collectionCopy[id]) ||  !(collectionCopy[id]
     ["tracks"].constructor === Array)){
       collectionCopy[id]["tracks"]=[];
   }
   collectionCopy[id]["tracks"].push(value);      

}
if(prop == "tracks")
  {
    if(!Array.isArray(collectionCopy[id]["tracks"]){
      collectionCopy[id]["tracks"] = [];
    }
    collectionCopy[id]["tracks"].push(value);
  }

create an array if it is not an array first 如果不是数组,则创建一个数组

You can't push onto an array property if it hasn't been initialized yet. 如果尚未初始化数组属性,则不能将其推入。 You can use the following trick: 您可以使用以下技巧:

if(prop == "tracks")
{
  (collectionCopy[id]["tracks"] = collectionCopy[id]["tracks"] || []).push(value);
}

If the array is initilized, then collectionCopy[id]["tracks"] || [] 如果数组已初始化,则collectionCopy[id]["tracks"] || [] collectionCopy[id]["tracks"] || [] evaluates to collectionCopy[id]["tracks"] || [] collectionCopy[id]["tracks"] || []计算为collectionCopy[id]["tracks"] || [] collectionCopy[id]["tracks"] || [] , otherwise it will evaluate to [] thus a new property of array type being initialized. collectionCopy[id]["tracks"] || [] ,否则它将求值为[]因此将初始化array类型的新属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM