How to filter Object using Array.prototype.filter?

后端 未结 6 1644
夕颜
夕颜 2020-12-03 22:52

Given

var arr = [1,2,true,4,{\"abc\":123},6,7,{\"def\":456},9,[10]]

we can filter number items within array arr using N

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 23:49

    In ES6 the following would do it for the example values you have listed:

    arr.filter(Object.isExtensible)
    

    Obviously, this will exclude objects that have been marked non-extensible, by a call to Object.freeze, Object.seal, or Object.preventExtensions. Unless you plan to use those, I believe this does the job.

    var arr = [
        /* primitives: */
        2, true, "str", null, undefined, NaN, 
        /* objects */
        new Number(2), {a:1}, Object.create(null), [10], x=>x, new Date(), new Set()
    ];
    
    var objects = arr.filter(Object.isExtensible);
    
    console.log(objects);

提交回复
热议问题