猿问

js 循环取出对象的属性

一个对象


state={

    new1:1,

    new2:2,

    new3:3,

    old1:1,

    old2:2

}

我如果想循环取出 state.new1 state.new2state.new3的值应该怎么取

不取出old1 old2


例如第一次循环得到 state.new1 第二次得到 state.new2


for(var i=0;i<3;i++){

    第一次循环得到 state.new1 

    第二次得到 state.new2

}


拉风的咖菲猫
浏览 708回答 5
5回答

森栏

let state={&nbsp; &nbsp; new1:1,&nbsp; &nbsp; new2:2,&nbsp; &nbsp; new3:3,&nbsp; &nbsp; old1:1,&nbsp; &nbsp; old2:2};const BLACK_LIST = ["old1", "old2"];for(let p in state) {&nbsp; &nbsp; if(BLACK_LIST.indexOf(p) == -1)&nbsp; &nbsp; &nbsp; &nbsp; console.log(p, state[p])}

紫衣仙女

for(var value in state){&nbsp; &nbsp; console.log(state[value])}

泛舟湖上清波郎朗

对象用for in循环const state = {&nbsp; news1: 1,&nbsp; news2: 2,&nbsp; news3: 3,&nbsp; old: 1,&nbsp; old2: 2}var arr = []for (let o in state) {&nbsp; if (o.indexOf('news') > -1) {&nbsp; &nbsp; arr.push({[o]: state[o]})&nbsp; }}console.log(arr)

慕雪6442864

可以把不想枚举的属性的enumerable设置为false,这样for in的话就不会循环出来了:function notEnum (obj, keys) {&nbsp; keys.forEach(key => {&nbsp; &nbsp; let def = Object.getOwnPropertyDescriptor(obj, key)&nbsp; &nbsp; def.enumerable = false&nbsp; &nbsp; Object.defineProperty(obj, key, def)&nbsp; })}var state = {&nbsp; &nbsp; new1:1,&nbsp; &nbsp; new2:2,&nbsp; &nbsp; new3:3,&nbsp; &nbsp; old1:1,&nbsp; &nbsp; old2:2}notEnum(state, ['old1', 'old2']) // 把old1和old2设置为不可枚举属性for (let i in state) {&nbsp; console.log(i)}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答