[英]Javascript strange behavior in Json Object Manipulation
我真的無法掌握那里發生的一切,我真的認為我應該與你們分享:
我正在'/ products'上調用我的api,響應在郵遞員中看起來像這樣:
[
{
"id": 2,
"name": "some_product_name",
"description": "description",
"price": "$120.00",
"firmware_version": "1.0",
"quantity_in_stock": 50,
"selling": true,
"build_version": "1.2",
"category_id": 1,
"available_colors": [
{
"name": "blue",
"in_stock": true,
"picture": {
"type": "Buffer",
"data": []
}
},
{
"name": "black",
"in_stock": true,
"picture": null
},
{
"name": "silver",
"in_stock": true,
"picture": {
"type": "Buffer",
"data": []
}
}
]
}
]
現在,我要在這里創建一個名為products_showcase的新對象,該對象對每種產品顏色都有一個條目,除了可用顏色屬性之外,其他信息都相同,由顏色對象代替:
$scope.initModel = function() {
$http({
method: 'GET',
url: '/products'
}).then(function(resp) {
console.log(resp.data);
$scope.products = resp.data;
$scope.products.forEach((item, index, array) => {
item.available_colors.forEach((color, index, array) => {
var product = item;
product.color = {};
product.color = color;
delete product['available_colors'];
$scope.products_showcase.push(product);
});
});
}, function(error) {
$scope.error = error;
});
};
但是隨后,發生了一件非常奇怪的事情:
將JavaScript分配給變量時,它不會創建新對象。 您可以使用Object.create函數從現有對象創建一個新對象。
$scope.initModel = function() {
$http({
method: 'GET',
url: '/products'
}).then(function(resp) {
console.log(resp.data);
$scope.products = Object.create(resp.data);
$scope.products.forEach((item, index, array) => {
item.available_colors.forEach((color, index, array) => {
var product = Object.create(item);
product.color = {};
product.color = color;
delete product['available_colors'];
$scope.products_showcase.push(product);
});
});
}, function(error) {
$scope.error = error;
});
};
Javascript賦值運算符顯然不會為新變量創建對象的新實例,而只是創建指向“父親”對象的內存地址的指針。
示例代碼:
var object = {property: 'myProp'};
console.log(object);
{屬性:“ myProp”}
var newObj = object;
newObj.newProperty = 'myNewProp';
console.log(object);
{屬性:“ myProp”,新屬性:“ myNewProp”}
要創建對象的新實例,我們必須使用Object.create()方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.