将值推送到对象数组

时间:2016-06-14 15:16:32

标签: javascript arrays

我似乎无法弄清楚为什么我无法在下面的数组中附加值?在构造数组时是否需要遵循特殊的语法或类似于下面使用的方法?

<div class="col-md-8">
<div class="well main-well">
    <h3 class="page-header-h3">Following Dashboard:</h3>
    <hr />
    <h4 align="center" ng-show="!captures.length">
                        <strong>The people that you are following, have not posted anything yet.. Yikes!</strong>
                        <br /><br />
                        Quickly, go follow more people!</h4>
    <div class="row" infinite-scroll="nextPage()" infinite-scroll-disabled="busy || noMoreData" infinite-scroll-distance="0.1">
        <ul class="dynamic-grid" angular-grid="captures" ag-id="gallery">
            <li data-ng-repeat="capture in captures | orderBy :'created_at':true" class="grid">
                 <a ui-sref="detail({id: capture._id})">
                     <img ng-src="{{capture.picture}}" class="grid-img" />
                     <span class="follow-capture-info">
                        <span class="follow-capture-name"><span class="glyphicon glyphicon-user"></span> 
                          {{capture.author}} 
                            <span class="following-capture-time">· 
                                <span class="glyphicon glyphicon-time"></span> 
                                <span am-time-ago="capture.created_at"></span>
                            </span>
                        </span>
                    </span>
                 </a>
            </li>
        </ul>
    </div>
    <div ng-show="busy">Loading more...</div>
</div>

5 个答案:

答案 0 :(得分:4)

尝试:arr.fruits.push("mango");

答案 1 :(得分:2)

你不能push()对象。您应该使用键值表示法:

arr.anotherFruits = "testing123"; // another key
arr.fruits = "testing123"; //to overwrite

或者让arr实际上是数组:

var arr = [
    {"fruits": ['apple','banana','orange']}
]

arr.push({ "fruits":"testing123"})

alert(arr["fruits"])

在这种情况下,你会得到

var arr = [
    {"fruits": ['apple','banana','orange']},
    {"fruits":"testing123"}
]

或者如果您确实想要获得这样的对象

var arr = {
    "fruits": ['apple','banana','orange','testing123']
}

你应该使用arr.fruits.push('testing123');

答案 2 :(得分:1)

你的array定义完全没错。假设您希望arrobject arrayfruits,然后在fruits内推送另一个值,请使用以下内容:

&#13;
&#13;
var arr = {
    fruits: ['apple', 'banana', 'orange']
};
arr.fruits.push("testing123");
console.log(arr["fruits"]);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

将您的初始arr声明更改为此...

var arr = [{
    "fruits": ['apple','banana','orange']
}];

然后你可以将更多的物体推到它上面。 E.g。

arr.push({"fruits": ['mango', 'pear', 'tomato']});

或者,如果您希望将水果推送到现有数组INSIDE您的对象,那么只需使用您现有的arr声明并像这样使用它......

arr.fruits.push('tomato');
arr.fruits.push('pear');
arr.fruits.push('tomato');

我认为你根本不需要这个就是这里的对象。

你只需要这个......

var fruits = [];
fruits.push('banana');
fruits.push('apple');

它只是一系列水果。如果您需要更复杂的结构,则使用对象数组而不是字符串。

答案 4 :(得分:0)

数组有push()方法,但对象没有。在这里创建一个Object,但不是一个Array。所以它失败了。