js 对象、数组互转

26 篇文章 0 订阅

如题

1. 如何判断返回数据类型

首先:

typeof的返回值共有七种:
number, boolean, string, undefined, object, function,symbol.

1、number

typeof(10);
typeof(NaN);
//NaN在JavaScript中代表的是特殊非数字值,它本身是一个数字类型。
typeof(Infinity);

2、boolean

typeof(true);
typeof(false);

3、string

typeof(“abc”);

4、undefined

typeof(undefined);
typeof(a);//不存在的变量

5、object

对象,数组,null返回object
typeof(null);
typeof(window);

6、function

typeof (Array)

typeof(Date)

7、symbol

typeof Symbol() // ES6提供的新的类型

根据以上我们知道,对于对象和数组,typeof返回的都是Object,那么,如何获取返回数据的数据类型呢?

① typeof + length:
let a = {"name": "zhangsan"};
let b = [0,1,2];
var getDataType = function(o){
    if(typeof o == 'object'){
        if( typeof o.length == 'number' ){
            return 'Array'; 
        }else{
            return 'Object';    
        }
    }else{
        return 'param is no object type';
    }
};

② instance(简单,推荐):

alert( a instanceof Object );  // true
alert( b instanceof Array );  // true

判断确认数据类型后,就需要根据需求进行一系列转化了。

2. 对象 ——> 数组

(对象数组转为数组):

let objTest = {
	 arr1: [1,2,3],
	 arr2: [7, 8, 9],
	 arr3: ["zhangsan", 15, "男"]
};
console.log(objTest instanceof Object);  // 判断objTest数据类型是不是对象
let arrList2 = [];
for (let i in objTest) {
  arrList2.push(objTest[i]);
}
console.log(arrList2);

(对象属性转为数组):

let obj = {
    arr1: [1,2,3],
    arr2: [7, 8, 9],
    arr3: ["zhangsan", 15, "男"]
};
let obj1 = {"name": "zhangsan", "age": 10};
// ...

let arr4 = Object.keys(obj);
console.log(arr4);   // ['arr1', 'arr2', 'arr3']
let arr5 = Object.keys(obj1);
console.log(arr5);  // ['name', 'age']

(对象值转为数组):

let obj = {
    arr1: [1,2,3],
    arr2: [7, 8, 9],
    arr3: ["zhangsan", 15, "男"]
};
let obj1 = {"name": "zhangsan", "age": 10};
// ...

let arr4 = Object.values(obj);
console.log(arr4);   // [[1,2,3], [7,8,9], ["zhangsan", 15, "男"]]
let arr5 = Object.values(obj1);
console.log(arr5);  // ['zhangsan', 10]

(特殊——Array.from(object)):
from() 方法从具有 length 属性或可迭代对象的任何对象返回 Array 对象。
object中必须有length属性,返回的数组长度取决于length长度。
key值必须为数值。(亲测非数值转换失败)

let obj = {
    1: [1,2,3],
    2: [7, 8, 9],
    3: ["zhangsan", 15, "男"]
};
let obj1 = {"name": "zhangsan", "age": 10};

let arr = Array.from(obj);  //object中必须有length属性,返回的数组长度取决于length长度;key值必须为数值
3. 数组 ——> 对象
// 数组转对象
var arr = [1,2,3,4,5,6]
let obj = {}


// 1.使用for in 遍历
for(let key in arr) { //这里key索引
  obj[key] = arr[key]
}


// 2.使用es6展开运算符
let obj = {...arr}

// 3.使用for循环
for(let i = 0; i < arr.length; i ++) {
  obj[arr[i]] = arr[i]; //数组转为对象,对象的键=数组值, 对象的值=数组值
}

// 4. assign
obj = (Object.assign({}, array)
console.log(obj);// {1,2,3,4,5,6}

自律体现在选择此时想要的还是最终最想要的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值