Knockout.js console.log可观察数组

9rygscc1  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(134)

我像往常一样尝试通过JSON.stringify将console.log记录可观察数组内容的阶段,但没有成功。我看到长度发生了变化,但内容没有变化。
编码:

arr.push(new Course('New title ' + randomCourse, 'New price ' + randomCourse));
console.log('CourseList: ' + arr().length + ' | ' + JSON.stringify(arr()));

控制台:

CourseList: 5 | [{},{},{},{},{}]
CourseList: 7 | [{},{},{},{},{},{},{}]
CourseList: 9 | [{},{},{},{},{},{},{},{},{}]
CourseList: 11 | [{},{},{},{},{},{},{},{},{},{},{}]
rta7y2nd

rta7y2nd1#

您可能应该使用ko.toJS()将可观察的属性转换为值:

console.log('CourseList: ' + arr().length + ' | ' + JSON.stringify(ko.toJS(arr())));
a11xaf1n

a11xaf1n2#

嗯,一下子变得不那么简单了,调试中绝对没有任何错误。
任务是在其他操作之前将数组项推送到可观察数组。
功能(如果注解,则为控制台):

this.startCoursesList = function () {
    if (arr.length === 0) {
        startCourses.forEach(function (item, i) {
            arr.push(new Course(startCourses[i].title, startCourses[i].price, startCourses[i].reqs));
        });
        // console.log(JSON.stringify(ko.toJS(arr())));
    }
};

一切都很好,控制台很清晰,但是如果我使用JSON.stringify(ko.toJS(arr())),一切都失败了。突然我得到了函数执行循环和arr.length检查,如果不工作的话。我还得到了任何点击事件的控制台循环:

[{"title":"HTML/CSS","price":32000,"reqs":["Internet","Notepad++"]},{"title":"Yoga","price":7000,"reqs":[""]},{"title":"Darts","price":9500,"reqs":["Bomb","Worms"]}]
[{"title":"HTML/CSS","price":32000,"reqs":["Internet","Notepad++"]},{"title":"Yoga","price":7000,"reqs":[""]},{"title":"Darts","price":9500,"reqs":["Bomb","Worms"]}]
[{"title":"HTML/CSS","price":32000,"reqs":["Internet","Notepad++"]},{"title":"Yoga","price":7000,"reqs":[""]},{"title":"Darts","price":9500,"reqs":["Bomb","Worms"]}]

相关问题