一、JS轉數組的方法
JavaScript中,我們可以使用多種方法將字元串、集合或類數組轉換為數組。下面是一些實用的JS轉數組的方法:
1. Array.from()
const str = 'hello';
const arr = Array.from(str);
console.log(arr); // ['h', 'e', 'l', 'l', 'o']
Array.from()方法將字元串轉換為字元數組。
2. slice()
const str = 'hello';
const arr = Array.prototype.slice.call(str);
console.log(arr); // ['h', 'e', 'l', 'l', 'o']
slice()方法將字元串轉換為字元數組,然後使用函數調用將該數組複製到新數組中。
3. split()
const str = 'hello world';
const arr = str.split(' ');
console.log(arr); // ['hello', 'world']
split()方法將字元串分割為數組。
二、JS數組去重
數組去重是常見的操作,避免相同的值被計算多次。下面是幾種常用的JS數組去重方法:
1. 藉助Set去重
const arr = [1, 2, 2, 3, 4, 4, 5];
const newArr = Array.from(new Set(arr));
console.log(newArr); // [1, 2, 3, 4, 5]
使用Set去重,然後轉化為數組。
2. 使用forEach去重
const arr = [1, 2, 2, 3, 4, 4, 5];
let newArr = [];
arr.forEach((item) => {
if (!newArr.includes(item)) {
newArr.push(item);
}
});
console.log(newArr); // [1, 2, 3, 4, 5]
使用forEach()循環數組,判斷元素是否在新數組中,如果不存在則添加到新數組中。
三、數組轉字元串JS/字元串轉數組JS
在JavaScript中,我們可以輕鬆地將數組轉換為字元串或將字元串轉換為數組。
1. 數組轉字元串JS
const arr = ['h', 'e', 'l', 'l', 'o'];
const str = arr.join('');
console.log(str); // 'hello'
使用join()方法將數組轉換為字元串。
2. 字元串轉數組JS
const str = 'hello';
const arr = str.split('');
console.log(arr); // ['h', 'e', 'l', 'l', 'o']
使用split()方法將字元串分割為字元數組。
四、數組轉JSON
JavaScript中的數組轉JSON是一種將數據從JS格式轉換為JSON格式的方法,JSON格式的數據可以用於Web應用程序之間的數據交換。
const arr = [{name:'John', age:20}, {name:'Mary', age:18}];
const json = JSON.stringify(arr);
console.log(json); // '[{"name":"John","age":20},{"name":"Mary","age":18}]'
使用JSON.stringify()方法將數組對象轉換為JSON字元串。
五、JS數組反轉/數組反轉JS
在JavaScript中,我們可以使用reverse()方法反轉數組。
const arr = ['h', 'e', 'l', 'l', 'o'];
const reverseArr = arr.reverse();
console.log(reverseArr); // ['o', 'l', 'l', 'e', 'h']
使用reverse()方法反轉數組。
六、JS轉字元串/JS數組循環/JS數組轉換為對象
1. JS轉字元串
const obj = {name:"John", age:20};
const str = JSON.stringify(obj);
console.log(str); // '{"name":"John","age":20}'
使用JSON.stringify()方法將對象轉換為JSON字元串。
2. JS數組循環
const arr = ['h', 'e', 'l', 'l', 'o'];
arr.forEach(function (item) {
console.log(item);
});
使用forEach()方法循環遍曆數組。
3. JS數組轉換為對象
const arr = [['name', 'John'], ['age', 20]];
const obj = Object.fromEntries(arr);
console.log(obj); // { name: 'John', age: 20 }
使用Object.fromEntries()方法將數組轉換為對象。
總結
在JavaScript中,我們可以輕鬆地將字元串、集合或類數組轉換為數組,去重數組,將數組轉換為字元串或將字元串轉換為數組,將數組對象轉換為JSON字元串以進行數據交換,並使用reverse()方法反轉數組。我們還可以使用forEach()方法循環數組和使用Object.fromEntries()方法將數組轉換為對象。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/239248.html