请写出一个数组拍平函数,效果如下:
var arr=['a', ['b', 'c'], 2, ['d', 'e', 'f'], 'g', 3, 4];
flat(arr) //a,b,c,2,d,e,f,g,3,4
var arr =['a', ['b', 'c'], 2, ['d', 'e', 'f'], 'g', 3, 4];
function flat(arr) {
return arr.toString().split(',').map(function(item){
return Number(item)
})
}
console.log(flat(arr))
var arr = ['a', ['b', 'c'], 2, ['d', 'e', 'f'], 'g', 3, 4];
// 方法二:toString(格式转换)
var flag = function(arr) {
let toString = Array.prototype.toString;
Array.prototype.toString = function() {
return this.join(',');
};
let result = arr + '';
Array.prototype.toString = toString;
return result;
};
console.log(flag(arr));
// 方法三:valueOf(格式转换)
Array.prototype.valueOf = function() {
return this.join(',');
};
var flat = function(arr) {
return arr + '';
};
console.log(flat(['a', ['b', 'c'], 2, ['d', 'e', 'f'], 'g', 3, 4]));
function flat(arr) {
return newArr = arr.reduce((a, b) => {
return a.concat(b)
}, [])
}
var arr = ['a', ['b', 'c'], '2', ['d', 'e', 'f'], 'g', 3, 4];
console.log(flat(arr));
function flat(array) {
var result = [];
var each = function(arr) {
arr.forEach(item => {
if (item instanceof Array) {
each(item);
} else {
result.push(item);
}
});
};
each(array);
return result.join(',');
}
var arr = ['a', ['b', 'c', [7, 8]], 2, ['d', 'e', 'f'], 'g', 3, 4];
console.log(flat(arr));
// Iterator
Array.prototype[Symbol.iterator] = function() {
let arr = [].concat(this);
// arr=['a', ['b', 'c'], '2', ['d', 'e', 'f'], 'g', 3, 4]
let getFirst = function(array) {
let first = array.shift();
if (first instanceof Array) {
if (first.length > 1) {
arr = first.slice(1).concat(array);
}
first = first[0];
}
return first;
};
return {
next: function() {
//类似与遍历
let item = getFirst(arr);
if (item) {
return {
value: item,
done: false,
};
} else {
return {
done: true,
};
}
},
};
};
var flat = function(arr) {
let r = [];
for (let i of arr) {
r.push(i);
} // i 已经是单个元素
return r.join(',');
};
var arr = ['a', ['b', 'c'], '2', ['d', 'e', 'f'], 'g', 3, 4];
console.log(flat(arr));