类数组对象转换为对象

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script>
			// 方法一:for in 
			{
				let obj = {
					'未完成': 5,
					'已完成': 8,
					'待确认': 4,
					'已取消': 6
				};
				let arr = []
				for (let i in obj) {
					arr.push(obj[i]);
				}
				console.log(arr);

				//如果是push整个对象
				let arr1 = []
				for (let i in obj) {
					let newobj = {}
					newobj[i] = obj[i]
					arr1.push(newobj);
				}
				console.log(arr1);
			}

			//第二种方法  Object.keys / Object.values
			{
				let obj = {
					'未完成': 5,
					'已完成': 8,
					'待确认': 4,
					'已取消': 6
				};
				let arr1 = Object.keys(obj)
				console.log(arr1);
				let arr2 = Object.values(obj)
				console.log(arr2);
			}


			// 第三种方法  Array.from
			{
				let obj = {
					'未完成': 5,
					'已完成': 8,
					'待确认': 4,
					'已取消': 6,
					'length': 4
				};
				let arr = Array.from(obj)
				console.log(arr);
				// 1、 该类数组对象必须具有length属性, 用于指定数组的长度。
				// 		如果没有length属性, 那么转换后的数组是一个空数组。
				// 2、 该类数组对象的属性名必须为数值型或字符串型的数字
				// ps: 该类数组对象的属性名可以加引号, 也可以不加引号
				let arrayLike = {
					0: 'tom',
					1: '65',
					2: '男',
					3: ['jane', 'john', 'Mary'],
					'length': 4
				};
				let ary1 = Array.from(arrayLike)
				console.log(ary1)
			}

			// 第四种方法 for of 和 for in 
			{
				/* for of中item代表数组中每一项的值 
				for in 中i代表数组中的索引 对象中的每一项的key值*/
				let arr = ['a', 'b', 'c'];
				for (let item of arr) {
					console.log(item);
				}
				for (let item in arr) {
					console.log(item);
				}

				let obj = {
					'qqq': 'a',
					'www': 'b',
					'eee': 'c'
				};

				// for of 不能用于对象,只能遍历数组 
				// for (let item of obj) {
				// 	console.log(item);  // obj is not iterable
				// }

				//  for in 可以用于对象 
				for (let item in obj) {
					console.log(item); // 属性名
				}
			}

			// 第五种方法 Array.prototype.slice.call()方法
			{
				let arrayLike = {
					0: 'tom',
					1: '65',
					2: '男',
					3: ['jane', 'john', 'Mary'],
					'length': 4
				}
				let list = Array.prototype.slice.call(arrayLike);
				console.log(list);

				let obj = {
					'未完成': 5,
					'已完成': 8,
					'待确认': 4,
					'已取消': 6,
					'length': 4
				};
				let arr = Array.prototype.slice.call(obj);
				console.log(arr); // 空数组  对对象无效
			}

			// 第六种方法:利用拓展运算符
			{
				// 获取的DOM元素节点列表
				let oDivs = document.getElementsByTagName('div');
				oDivs = [...oDivs];
				console.log(oDivs);
			}
		</script>

	</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值