gpt4 book ai didi

javascript - 如何检查对象在knockout js中是否有任何属性

转载 作者:行者123 更新时间:2023-11-30 10:02:08 25 4
gpt4 key购买 nike

knockout js中如何判断observable对象是否存在属性
我已经尝试使用 hasOwnProperty 并且它总是返回 false 给我。

我的代码如下:

    <div data-bind="click:setObject">Click here</div>
<div data-bind="click:init">check console</div>
<script>
var ViewModel = function() {
var self = this;
this.arrayVal = ko.observable({});
this.setObject = function(){ /* i have set property here */
self.arrayVal({
id:10
});
};
self.init = function(){
console.log(self.arrayVal());
console.log(self.arrayVal.hasOwnProperty('id')); /* on second click (after setObject ) i expect trut,but it returned false */
}
self.init();
};
ko.applyBindings(new ViewModel());
</script>

最佳答案

您需要获取 arrayVal observable 中的值:

console.log(self.arrayVal().hasOwnProperty('id'));

Observable 本身有方法 hasOwnProperty 但没有属性 id,因此

self.arrayVal.hasOwnProperty('id');    // false, 'id' doesn't exist on the observable

同时

self.arrayVal().hasOwnProperty('id');    // true, 'id' exists on the observable's value

关于javascript - 如何检查对象在knockout js中是否有任何属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31049384/

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