data.push({"country": "IN"});
爲新的ID和價值JSON字符串。但它提供了以下錯誤的回覆
Uncaught TypeError: data.push is not a function
data{"name":"ananta","age":"15"}
先感謝
data.push({"country": "IN"});
爲新的ID和價值JSON字符串。但它提供了以下錯誤的回覆
Uncaught TypeError: data.push is not a function
data{"name":"ananta","age":"15"}
先感謝
要使用Array的push函數,你的var需要是一個Array。
更改data{"name":"ananta","age":"15"}
到以下幾點:
var data = [
{
"name": "ananta",
"age": "15",
"country": "Atlanta"
}
];
data.push({"name": "Tony Montana", "age": "99"});
data.push({"country": "IN"});
..
含數組項將typeof運算對象,你可以做到以下幾點:
var text = "You are " + data[0]->age + " old and come from " + data[0]->country;
注意:儘量保持一致。在我的示例中,一個數組包含對象屬性name
和age
,而另一個僅包含county
。如果我用for
或forEach
迭代這個,那麼我不能總是檢查一個屬性,因爲我的示例包含改變的項目。
完美的將是:data.push({ "name": "Max", "age": "5", "country": "Anywhere" });
所以,你可以循環,總是可以得到的屬性,即使它們是空的,null或undefined。
編輯
酷的東西知道:
var array = new Array();
是類似於:
var array = [];
另外:
var object = new Object();
是西米拉爾:
var object = {};
您也可以將它們組合起來:
var objectArray = [{}, {}, {}];
你data
變量中包含的對象,而不是一個數組,對象不具備push
功能的錯誤狀態。要做到你需要,你可以這樣做的:
data.country = 'IN';
或者
data['country'] = 'IN';
假設我有國家作爲變量,我想傳遞變量值,我該如何實現這樣的事情? –
@HarshPatel第二個使用括號表示法的例子可以處理變量:'var propertyName ='country'; data [propertyName] ='IN';' –
可以使用按鍵方法僅如果對象是一個數組:
var data = new Array();
data.push({"country": "IN"}).
OR
data['country'] = "IN"
如果它只是一個可以使用的對象
data.country = "IN";
試試這個代碼$ scope.DSRListGrid.data =數據;這一個源數據
for (var prop in data[0]) {
if (data[0].hasOwnProperty(prop)) {
$scope.ListColumns.push(
{
"name": prop,
"field": prop,
"width": 150,
"headerCellClass": 'font-12'
}
);
}
}
console.log($scope.ListColumns);
確保您推爲Array只有 ,如果他們像遺漏的類型錯誤錯誤:data.push不是一個函數** 然後檢查類型的數據 您可以通過consol.log(數據) 希望做到這一點,這將有助於
好的謝謝你的回覆 –
因爲'data'不是'Array'。如果它是'object',只需設置'date.country ='IN''。如果它是「JSON字符串」,則最好先將其反序列化。 – haim770
'data.country ='IN'' –
確保您不要執行「data = data.push(...)」。這也會導致上述錯誤。 –