取出嵌套数组的所有成员:
function* iter(arr){
if(Array.isArray(arr)){
for(let i=0;i<arr.length;i++){
yield* iter(arr[i]);
}
}
else{
yield arr;
}
}
let arr=[1,2,[7,[4,[5,3]]]];
for(let x of iter(arr)){
console.log(x);
}
一、转字符串法
let arr=[1,2,[7,[4,[5,3]]]];
let result=arr.join(",").split(",");
console.log(result); //["1", "2", "7", "4", "5", "3"]
二、toString()
var a = [1,3,4,5,[6,7,9],[2],[5]];
a = a.toString().split(",");
console.log(a); //["1", "3", "4", "5", "6", "7", "9", "2", "5"]
三、递归
使用Object.prototype.toString.call()来判断array的类型,也可以使用Array.isArray来判断。
let result = [];
function iter(arr){
for(let item of arr){
if(Object.prototype.toString.call(item).slice(8, -1)==='Array'){
iter(item);
}else{
result.push(item);
}
}
return result;
}
let arr4 = ['1',2,[3,4,[5,6]],7];
console.log(iter(arr4)); // ["1", 2, 3, 4, 5, 6, 7]
【补充】为什么用Object.prototype.toString.call(obj)检测对象类型?
问题1:使用typeof bar === "object"检测”bar”是否为对象有什么缺点?如何避免?
- 用 typeof 不能准确判断一个对象变量,null 的结果也是 object,数组的结果也是 object,有时我们需要的是 “纯粹” 的 object 对象。如何避免呢?比较好的方式是:
console.log(Object.prototype.toString.call(obj) === "[object Object]");
问题2:为什么不直接用obj.toString()?
- toString为Object的原型方法,而Array 、Function等类型作为Object的实例,都重写了toString。
- 不同的对象类型调用toString方法时,根据原型链知识,调用的是对应的重写之后的toString方法(Function类型返回内容为函数体的字符串,Array类型返回元素组成的字符串),而不会去调用Object上原型toString方法(返回对象的具体类型)。
- 采用obj.toString()不能得到其对象类型,只能将obj转换为字符串类型;因此,在想要得到对象的具体类型时,应该调用Object上原型toString方法。
console.log("jerry".toString());//jerry
console.log((1).toString());//1
console.log([1,2].toString());//1,2
console.log(new Date().toString());//Wed Dec 21 2016 20:35:48 GMT+0800 (中国标准时间)
console.log(function(){}.toString());//function (){}
console.log(null.toString());//error
console.log(undefined.toString());//error
使用Object.prototype.toString.call():
console.log(Object.prototype.toString.call("jerry"));//[object String]
console.log(Object.prototype.toString.call(12));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
function Person(){};
console.log(Object.prototype.toString.call(new Person));//[object Object]
四、concat()
只能将二维数组转为一维数组
let arr3 = [1,5,[6,[7,8]],[2],[5]];
console.log([].concat.apply([],arr3)); //[1, 5, 6, Array(2), 2, 5]