我想分配一個JS中的關聯數組風格的對象,但它失敗,說'task.id'是未定義的。爲什麼是這樣?JavaScript中的關聯風格數組?
var response = Object();
$('.task-list').each(function() {
response[this.id][$('#' + this.id).sortable('toArray')];
});
我想分配一個JS中的關聯數組風格的對象,但它失敗,說'task.id'是未定義的。爲什麼是這樣?JavaScript中的關聯風格數組?
var response = Object();
$('.task-list').each(function() {
response[this.id][$('#' + this.id).sortable('toArray')];
});
您正在將對象引用爲二維數組。
你應該這樣做更多的是這樣的:
var response = {};
$(".task-list").each(function() {
response[this.id] = $(this).sortable('toArray');
}
此外,當你說的錯誤是「task.id是不確定的」,你的意思是「this.id是未定義」?如果您選擇基於類的元素,則可能沒有明確的ID。
<span class="task-list">myTask</span>
您可能要包括ID:
<span class="task-list" id="myTask">myTask</span>
您正試圖訪問您尚未創建的屬性。儘管實際情況並不清楚你在示例中要做什麼。我假設你想將response[this.id]
的值設置爲$('#' + this.id).sortable('toArray')
?
試試這個:
var response = {};
$('.task-list').each(function() {
response[this.id] = $(this).sortable('toArray');
});
也改變了它使用$(this)
而不是$('#' + this.id)
,因爲它是清潔海事組織。