<!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>
类数组对象转换为对象
最新推荐文章于 2024-04-26 17:11:06 发布