es6 - javascript数组自定义属性
黄舟
黄舟 2017-04-11 13:31:01
0
5
320

如下,关于javascript中数组的自定义属性,应该怎么理解

var ary = ["a", "b", "c"];
ary.name = "tom";
ary.age = 3;
console.log(ary); // ["a", "b", "c", name: "test"]
console.log(ary.length); // 3
console.log(Array.isArray(ary)); // true

console.log(ary.name); // "tom"
console.log(ary.age); // 3
ary.forEach(function (v) {
    console.log(v); // 依次打印 a b c
});
for (var prop in ary) {
    console.log(ary[prop]); // 依次打印 tom 3
}
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(5)
伊谢尔伦

没毛病,抛开name,其他都正常

[1,2] instanceof Object //true

数组也是对象
https://developer.mozilla.org...

不过一般不这么用吧 ~

黄舟

当做属性了呗。obj={};obj[0] = "数字作为变量名出线了。";console.log(obj);

伊谢尔伦

首先,谢邀

var ary = ["a", "b", "c"];
ary.name = "tom";
ary.age = 3;
console.log(ary); // ["a", "b", "c", name: "test"] //这里的name,就跟length一样理解就可以了。
console.log(ary.length); // 3
console.log(Array.isArray(ary)); // true

console.log(ary.name); // "tom"
console.log(ary.age); // 3
ary.forEach(function (v) {
    console.log(v); // 依次打印 a b c, //forEach只会遍历key为0,1,2,3...的value
});
for (var prop in ary) {
    console.log(ary[prop]); // 依次打印 tom 3 //for in 会遍历所有的key哟
}
小葫芦

var ary = ["a", "b", "c"];
ary[4] = "tom";
console.log(ary.length); // 5,数组空间的大小
js数组只支持数字索引
ary.name = "tom";
ary.age = 3;
非数字索引指的是对象的属性了

黄舟

谢邀。

var ary = ["a", "b", "c"];
ary.name = "tom";
ary.age = 3;
console.log(ary); // ["a", "b", "c", name: "test"] 
/*
    应该不会输出这个,age也会输出,如果你的没有显示 age,可能是因为后边显示不开了。
    我的Chrome输出结果如下,把console.log数组当作Object来处理了,但是又用[]来表示,应该属于展示的bug:
        ["a", "b", "c", name: "tom", age: 3]
    换成其他浏览器,比如IE11显示就正常的多了:
        [object Array]["a", "b", "c"]
*/

虽然 console.log 它 作为 Object 来处理(Array 也是一种 Object,typeof [] === "object"),连属性也输出了,但是他的真实的值还是没有 ["a", "b", "c"]

console.dir(ary);
/*
   Array[3]
     0: "a"
     1: "b"
     2: "c"
     age: 3
     length: 3
     name: "tom"
     __proto__: Array[0]
*/
ary;
/*
    而执行 ary,可以看到其真实的值:
    ["a", "b", "c"]
*/

随便换个 Object 类型 的 变量 测试,比如内置的String。

var str = new String("hello");
str.ageOrName = "tom";
console.log(str); 
/*
    String {0: "h", 1: "e", 2: "l", 3: "l", 4: "o", ageOrName: "tom", length: 5, [[PrimitiveValue]]: "hello"}
*/
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!