Object.key

Object.keys方法之详解

在实际开发中,我们有时需要知道对象的所有属性,原生js给我们提供了一个很好的方法:

Object.keys(),该方法返回一个数组

1.传入对象,返回属性名

var obj = {'a':'123','b':'345'};
console.log(Object.keys(obj));  //['a','b']

var obj1 = { 100: "a", 2: "b", 7: "c"};


console.log(Object.keys(obj1)); // console: ["2", "7", "100"]

var obj2 = Object.create({}, { getFoo : { value : function () { return this.foo } } });
obj2.foo = 1;
console.log(Object.keys(obj2)); // console: ["foo"]

2.传入字符串,返回索引

var str = 'ab1234';
console.log(Object.keys(obj));  //[0,1,2,3,4,5]

3.构造函数 返回空数组或者属性名

    function Pasta(name, age, gender) {
            this.name = name;
            this.age = age;
            this.gender = gender;
            this.toString = function () {
                    return (this.name + ", " + this.age + ", " + this.gender);
            }
    }
    console.log(Object.keys(Pasta)); //console: []

    var spaghetti = new Pasta("Tom", 20, "male");
    console.log(Object.keys(spaghetti)); //console: ["name", "age", "gender", "toString"]

4. 数组 返回索引

    var arr = ["a", "b", "c"];
    console.log(Object.keys(arr)); // console: ["0", "1", "2"]

Object.keys 只收集自身属性名,不收集继承自原型链上的

forEach

forEach是ES5中操作数组的一种方法,主要功能是遍历数组,例如:

forEach方法中的function回调有三个参数:第一个参数是遍历的数组内容,第二个参数是对应的数组索引,第三个参数是数组本身

因此:

[].forEach(function(value,index,array){
 
    //code something
 
  });
 var arr = [1,2,3,4];
arr.forEach(function(value,index,array){
    array[index] == value;    //结果为true
    sum+=value;  
    });
console.log(sum);    //结果为 10

vue中

Object.keys(filters).forEach(key => Vue.filter(key, filters[key]))

原文地址:https://www.cnblogs.com/oneboi/p/7596633.html