2016-05-04 47 views
-1

我想知道如何將值添加到此數組中的main。將值添加到javascript中的數組(?)中的特定屬性

var herpderp = { 
    "main": ["stuff", "stuff"] 
}; 

所以它看起來像:

var herpderp = { 
    "main": ["stuff1", "stuff2", "stuff3"] 
}; 

最好,我想從幾個字符串在溫控功能創建這種結構如果可能的話。所以說我有這

var strings = {"stuff1","stuff2", "stuff3"} 
for (each element of strings) { 
    what do I do here to get the structure above 
} 

或者另一個函數來搜索特定屬性上的對象數組。現在我試圖用它來過濾數組,也許有另一種方式?

var arrays = search; 
var result = events.filter(function(item) { 
    for (var prop in arrays) 
     if (arrays[prop].indexOf(item[prop]) == -1) 
      return false; 
    return true; 
}); 

非常感謝您的回覆!

+2

[這裏是你如何訪問屬性(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors)。你可以使用['push'方法向數組添加東西](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)。我建議你通過幾個JavaScript教程來工作,直到你感覺舒適的操作對象和數組。 –

回答

0

herpderp.main是你的陣列,這樣你就可以添加到陣列中,像這樣:

herpderp.main.push(value)

如果您的陣列,關鍵是不是一個合法的變量名(它開始於一個號碼,例如) ,你可以使用括號記號來代替:

herpderp['123key'].push(value)

0

其實,要更改添加新的元素旁邊以前的值。

var herpderp = { 
     "main": ["stuff", "stuff"] 
}; 
var strings = ["stuff1","stuff2", "stuff3"]; 
strings.forEach(function(value,key){ 
herpderp.main[key] = value; 
}); 
console.log(herpderp); 
相關問題