1、在數組中添加對象,push()
let arr = [{a:1}]
let obj = {
b:2
}
arr.push(obj) //數組新增對象
2、數組轉換成字符串,並且用指定符合分割,join()
var joinArr = ["hello","world"];
var joinArr1 = joinArr.join(","); // joinArr1: "hello,world"
3、字符串轉換成數組,split()
var str = "hello,world"
var arr = str.split(",") //此處有個坑,如果str沒有值,arr也會加個,變成髒數據,所以我一般加個三元運算符
var arr = str ? str.split(",") : []
4、數組對象轉換成字符串,JSON.stringify
var data = JSON.stringify(data)
5、字符串轉換成數組對象,JSON.parse
var data = JSON.parse(data)
6、合併對象,Object.assign
const target = { a: 1, b: 1 };
const source1 = { b: 2, c: 2 };
const source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3} //如果對象有同名屬性,後面的屬性會覆蓋前面的屬性
7、合併數組
var arr1 = [1, 2, 3];
var arr2 = ["a","b","c","d","e","f"];
// 1、concat方法
var arr = arr1.concat(arr2); // [1, 2, 3, "a", "b", "c", "d", "e", "f"]
// 2、 通過for循環
for(let i in arr1){
arr2.push(arr[i]);
}
console.log(arr2) // [1, 2, 3, "a", "b", "c", "d", "e", "f"]
// 3、通過map()
arr1.map(item=>{
arr2.push(item)
});
console.log(arr2) // [1, 2, 3, "a", "b", "c", "d", "e", "f"]
// 4、apply
arr1.push.apply(arr1,arr2);
console.log(arr1) // [1, 2, 3, "a", "b", "c", "d", "e", "f"]
// 5、ES6 – 擴展運算符
arr = [...arr1,...arr2]
console.log(arr) // [1, 2, 3, "a", "b", "c", "d", "e", "f"]
8、合併數組去重
let arr1 = [1, 1, 2, 3, 6, 9, 5, 5, 4]
let arr2 = [1, 2, 5, 4, 9, 7, 7, 8, 8]
function uniqueArr(arr1,arr2) {
//合併兩個數組
arr1.push(...arr2)//或者arr1 = [...arr1,...arr2]
//去重
let arr3 = Array.from(new Set(arr1))//let arr3 = [...new Set(arr1)]
console.log(arr3)
}
uniqueArr(arr1,arr2)
9、合併數組,並根據對象中id的值去重
//數組1
let arr1 = [
{
id: 1,
name: "張三",
age: 18
},
{
id: 2,
name: "李四",
age: 18
},
{
id: 3,
name: "王五",
age: 18
}
];
// 數組2
let arr2 = [
{
id: 1,
name: "張三"
},
{
id: 2,
name: "李四"
}
];
arr1.push(...arr2); //合併數組
let hash = {}; //去重
let arr = arr1.reduce((preVal, curVal) => {
hash[curVal.id] //id就是數組中的id字段
? ""
: (hash[curVal.id] = true && preVal.push(curVal));
return preVal;
}, []);
console.log(arr); //此處數組根據id去重可參考我上一篇文章,這裏就不細說了。