程序猿头头(object与数组的简单应用)

object与数组的简单应用

new操作符

let person = new Object(); 
person.name = "Nicholas"; 
person.age = 29;

对象字面量

对象字面量是对象定义的简写形式,目的是为了简化包含大量属性的对象的创建。

let person = { 
    name: "Nicholas", 
    age: 29 
};

也可以使用字符串、数字、bool类型来定义。

let person = { 
    "name": "Nicholas", 
    "age": 29, 
    5: true,
	true: 123,
    false: 321
};
person[5];	//true
person[true];	//123
person[false];	//321

但要注意此类情况(后值覆盖前值):

let person = { 
    "name": "Nicholas", 
    "age": 29, 
    5: true,
	true: 123,
    true: 555,
    name: 'jack'
};
// 最后person变为
{
    5: true, 
    name: "jack", 
    age: 29, 
    true: 555
}

Array构造函数

let colors = new Array();	//表示创建一个空数组
colors.length;	//0

let colors = new Array(5);	//表示创建一个长度为5的空数组
colors.length;	//5
colors[0];	//undefined
let colors = Array(5); //不用new也可以

let colors = new Array("red", "blue", "green");	//表示创建一个数组,并传入三个值
colors.length;	//3
colors[0];	//"red"
let names = Array("Greg"); //不用new也可以

数组字面量

let colors = ["red", "blue", "green"]; // 创建一个包含3个元素的数组
let names = []; // 创建一个空数组
let values = [1,2,]; // 创建一个包含2个元素的数组
let ages = [,,,];	//创建一个包含3个三个空元素的数组
colors.length = 2;	//改变数组长度
colors[2];	//undefined

Array.from

第一个参数是一个类数组对象,即任何可迭代的结构,或者有一个 length 属性和可索引元素的结构。

// 字符串会被拆分为单字符数组 
console.log(Array.from("Matt")); // ["M", "a", "t", "t"]

// 可以使用from()将集合和映射转换为一个新数组
const s = new Set().add(1).add(2).add(3).add(4);
console.log(Array.from(s)); // [1, 2, 3, 4]

// Array.from()对现有数组执行浅复制
const a1 = [1, 2, 3, 4]; 
const a2 = Array.from(a1);
console.log(a1); // [1, 2, 3, 4]
a1 === a2; // false
a2.push(5);
a1.length;	//?

// arguments对象可以被轻松地转换为数组
function getArgsArray() { 
    return Array.from(arguments); 
}
console.log(getArgsArray(1, 2, 3, 4)); // [1, 2, 3, 4]

// from()也能转换带有必要属性的自定义对象
const arrayLikeObject = { 0: 1, 1: 2, 2: 3, 3: 4, length: 4 };
console.log(Array.from(arrayLikeObject)); // [1, 2, 3, 4]

//没有length的对象不行,因为会将0,1,2,3当做对象的key,而不当做是下标
const arrayLikeObject = { 0: 1, 1: 2, 2: 3, 3: 4 };
console.log(Array.from(arrayLikeObject)); // []
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值