gpt4 book ai didi

Javascript 迭代创建的动态对象

转载 作者:行者123 更新时间:2023-11-29 16:58:10 27 4
gpt4 key购买 nike

这是我的代码。问题在代码行中说明

<script>


// sample data created
var names = ['egard', 'roger'];

// object k is populated with a key and dynamic values
// depending on the list of names

// declare a new object
var k = {};

// create k properties according to names data
for (var i = 0; i < names.length; i++) {

if (k.hasOwnProperty(names[i])) {
k[names[i]] = false;
} else {
// value is dynamic, can be a number, char
// that will be used for other purposes
Object.defineProperty(k, names[i], {
value : true,
writable : true
});
}
};



// using jquery
$.each(k, function (i, me) {
// its not going here
console.log('jquery', me);
});

// using native iteration
for (var i in k) {
// its not going here
console.log('native', k[i]);
}

// what i want is to go inside the block
// of $.each or for ()
// so that i could iterate the object
// keys and its assign value

console.log(k);
// will output
Object {egard: true, roger: true}


console.log(k.egard);
// will output
// true
</script>

最佳答案

问题是您对 Object.defineProperty 的使用.默认情况下,它将创建不可枚举 属性,顾名思义,这些属性不能被您的循环枚举。只需将 enumerable 属性添加到定义中即可:

Object.defineProperty(k, names[i], {
value : true,
writable : true,
enumerable : true
});

这是一个 working version .

关于Javascript 迭代创建的动态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30390717/

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