1.来不及了,直接看代码吧
补充一点:
Object.keys 只收集自身属性名,不收集继承自原型链上的
Object.keys(obj),返回一个数组,数组里是该obj可被枚举的所有属性,以数组的形式返回。请看示例:
示例1
function Pasta(grain, width, shape) {
this.grain = grain;
this.width = width;
this.shape = shape;
this.toString = function () {
return (this.grain + ", " + this.width + ", " + this.shape);
}
}
console.log(Object.keys(Pasta)); //console: []
var spaghetti = new Pasta("wheat", 0.2, "circle");
console.log(Object.keys(spaghetti)); //console: ["grain", "width", "shape", "toString"]
console.log(Object.keys(Pasta)); //console: []
//解释,由于没有将构造函数实例化,所以只打印了一个空数组
实例化之后,就将构造函数所有的属性都作为一个数组进行返回
实例二
var arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // console: ["0", "1", "2"]
var obj = { 0 : "a", 1 : "b", 2 : "c"};
console.log(Object.keys(obj)); // console: ["0", "1", "2"]
var an_obj = { 100: "a", 2: "b", 7: "c"};
console.log(Object.keys(an_obj)); // console: ["2", "7", "100"]
var my_obj = Object.create({}, { getFoo : { value : function () { return this.foo } } });
my_obj.foo = 1;
console.log(Object.keys(my_obj)); // console: ["foo"]
当传入的是数组时候,返回的是数组的下标
是传入对象,则返回对应的属性
Object.assign
自己实现一个
if(typeof Object.assign != function){
Object.defineProperty(Object, 'assign', {
value: function(target, varArgs){
if(type target != null){
let to = Object(target);
for(var i=0; i< arguments.length; i++ ){
nextSource = arguments[index]
if(nextSource != null){
for (let nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to
}
},
writeable: true,
configurable: true
})
}