我正在尽我最大的努力来编写一个精确的应用程序。我在将空数组推入对象时遇到了问题。
我收到一个错误:
TypeError:无法读取未定义的属性“push”
我有一个名为items的对象,如下所示:
Object
{
"Name": "name",
"Description": "description"
}我想将一个空数组推入可以包含另一个数组的对象中。就像这样。
Object
{
"Name": "name",
"Description": "description",
"Related Items": {
Item1:{...},
Item2:{...},
...
}
}当调用它时,我的控制器会这样做:
$scope.push = function () {
$scope.item.push({"Related Items":[]});
};我知道我一定是被一些简单的JSON对象和数组搞混了,但我似乎找不到解决方案。
谢谢!
发布于 2014-10-06 16:50:45
由于item是一个对象,所以只需设置Related Items属性:
$scope.item["Related Items"] = [];
$scope.item["Related Items"].push({});但是,上面看起来Related Items实际上是一个具有键名Item1等的对象,而不是数组。
$scope.item["Related Items"] = {};
$scope.item["Related Items"].Item1 = {};发布于 2014-10-06 16:51:59
Javascript的push函数只有在将值推送到数组时才能工作。如果你试图推到一个对象,它将无法工作,相反,它将尝试调用不存在的" push“键。这就是为什么你得到了你要得到的错误。
确保$scope.item是一个数组([]或new Array),然后用您想要的值推送到它。
$scope.item = [];
$scope.push = function () {
$scope.item.push({"Related Items":[]});
};下面是 W3学校的.push()方法解释。
发布于 2014-10-06 17:00:28
项目对象应该是{.“相关物品”:<“一些价值”>.}
应该已经有钥匙了。
https://stackoverflow.com/questions/26220911
复制相似问题