[英]Object.assign(object1[i]) in javascript
假設object1有10個對象。 並且此代碼將object1分配給object2
const object2 = Object.assign(object1);
但是我只想使用for循環從object1分配5個對象。
for (let i = 0; i < 5; i++) {
object2 = Object.assign(object1[i]);
}
// but this one won't work.
有任何想法嗎?
var obj1 = [] for (let i=0; i< 10; i++) { obj1.push({key: i}); } var obj2 = [] for (let i=0; i< 5; i++) { obj2.push(obj1[i]); }
Object.assign()
。 用於將原始對象克隆或修改為目標對象 var obj1 = {key:1, foo: 'bar'}; var obj2 = Object.assign({}, obj1); //clone all properties var obj3 = Object.assign({foo: 'not bar', newprop: 'anything'}, obj1); //copy the original, modify `foo` property and add `newprop` //you can iterate through properties with this for (var property in obj3) { if (obj3.hasOwnProperty(property)) { // do stuff, may be filter which property you want to get, etc } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.