Javascript迭代动态对象创建

Oli*_* B. 2 javascript jquery properties object

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

<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>
Run Code Online (Sandbox Code Playgroud)

Jam*_*ice 5

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

Object.defineProperty(k, names[i], {
  value : true,
  writable : true,
  enumerable : true
});
Run Code Online (Sandbox Code Playgroud)

这是一个工作版本.