Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

类数组与push() #14

Open
yangxy6 opened this issue Jul 23, 2019 · 0 comments
Open

类数组与push() #14

yangxy6 opened this issue Jul 23, 2019 · 0 comments

Comments

@yangxy6
Copy link
Owner

yangxy6 commented Jul 23, 2019

类数组(ArrayLike)

  • 具有数字(索引)属性,对象的属性会被作为字符串处理
  • 必须具有 length 属性
  • 必有具有 splice 方法(实际测试)
  • 不具有数组其他方法

Array.prototype.push()

push 方法将值追加到数组中。
push 方法有意具有通用性。该方法和 call() 或 apply() 一起使用时,可应用在类似数组的对象上。push 方法根据 length 属性来决定从哪里开始插入给定的值。如果 length 不能被转成一个数值,则插入的元素索引为 0,包括 length 不存在时。当 length 不存在时,将会创建它。
唯一的原生类数组(array-like)对象是 Strings,尽管如此,它们并不适用该方法,因为字符串是不可改变的。
引用自MDN

举栗子

let obj = {
    '2': 2,
    '3': 3,
    length: 2,
    push: Array.prototype.push,
};
console.log(obj);
// 控制台:
{2: 2, 3: 3, length: 2, push: ƒ}
2: 2
3: 3
length: 2
push: ƒ push()
__proto__: Object
let obj = {
    '2': 2,
    '3': 3,
    length: 2,
    push: Array.prototype.push,
    splice: Array.prototype.splice
};
console.log(obj);
// 控制台
Object(2) [empty × 2, 2: 2, 3: 3, push: ƒ, splice: ƒ]
2: 2
3: 3
length: 2
push: ƒ push()
splice: ƒ splice()
__proto__: Object
let obj = {
    '0': 2,
    length: 2,
    push: Array.prototype.push,
    splice: Array.prototype.splice
};
console.log(obj);
// 控制台
Object(2) [2, empty, push: ƒ, splice: ƒ]
0: 2
length: 2
push: ƒ push()
splice: ƒ splice()
__proto__: Object
let obj = {
    '0': 2,
    // length: 2,
    push: Array.prototype.push,
    splice: Array.prototype.splice
};
console.log(obj);
// 控制台 {0: 2, push: ƒ, splice: ƒ}
let obj = {
    '1': 3,
    '2': 2,
    length: 2,
    push: Array.prototype.push,
    splice: Array.prototype.splice
    };
obj.push(1);
console.log(obj);
// 控制台
Object(3) [empty, 3, 1, push: ƒ, splice: ƒ]
1: 3
2: 1
length: 3
push: ƒ push()
splice: ƒ splice()
__proto__: Object

解析:obj具有length属性和splice方法,obj实际为类数组,push()方法具有通用性,obj的length=2,代表类数组前两项都是empty,push(1)时从下标为2开始之前2被替换成1,length长度也相应加1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant