gpt4 book ai didi

javascript - 数据订阅了 Knockout ObservableArray 但显示空数组

转载 作者:行者123 更新时间:2023-11-30 20:26:43 26 4
gpt4 key购买 nike

我是 JavaScript 的新手。我很难从位置 ObservableArray 打印数据。数据绑定(bind)有效,我可以在 View 中列出 ObservableArray 位置的数据,但无法在控制台上打印出来。我已经研究了几个小时了,如有任何帮助,我们将不胜感激。谢谢你

这是 ViewModel

    let MapViewModel = function() {

let map
let geocoder;
let self = this;

self.location = ko.observableArray([]);

for (let i = 0; i < locationList.length; ++i) {
self.location.push(new Location(locationList[i]));
}

console.log(this.location()); // Location, Location, Location, Location, Location, Location, Location]
console.log(this.location()[0].name); // Location {name: ƒ, address: ƒ} ...
console.log(this.location().length); //length is 7

}

let Location = function(data) {
this.name = ko.observable(data.name);
this.address = ko.observable(data.address);


}

ko.applyBindings(new MapViewModel());

这是绑定(bind)代码`

  <div class="menu_item_container">
<h1>Neighborhood Map</h1>
<input type="text" id="search" data-bind= 'value:filterLocations, valueUpdate: 'afterKeyDown',value:filterLocations' placeholder="Search Locations...">
<hr>
<nav id=nav>
<ul data-bind='foreach:location'>
<li data-bind="text:name"></li>
</ul>
</nav>
</div>

位置列表

  let locationList = [{
name: 'Brooklyn Museum',
address: '200 Eastern Pkwy, Brooklyn, NY 11238'
}, {
name: 'Empire State Building',
address: '350 5th Ave, New York, NY 10118'
}, {
name: 'Statue of liberty',
address: 'New York, NY 10004'
}, {
name: 'Rockefeller Center',
address: '45 Rockefeller Plaza, New York, NY 10111'
},
{
name: 'Brooklyn Bridge',
address: 'Brooklyn Bridge, New York, NY 10038'
},
{
name: 'Time Square',
address: '45 Rockefeller Plaza, New York, NY 10111'
},
{
name: 'World Trade Center',
address: '285 Fulton St, New York, NY 10007'
},
];

最佳答案

这可以将 observable 解包为常规 js 并将其转换为单个字符串(如果需要)然后你可以在控制台打印它:

let locationsJSON = ko.toJS(self.location);
let locationsString = JSON.stringify(locationsJSON);

关于javascript - 数据订阅了 Knockout ObservableArray 但显示空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50827333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com